代码之家  ›  专栏  ›  技术社区  ›  fadedbee

如何在Vec上把一个特征变成一个泛型?

  •  0
  • fadedbee  · 技术社区  · 3 年前

    我有一个工作特点:

    trait PopOrErr {
        fn pop_or_err(&mut self) -> Result<i8, String>;
    }
    
    impl PopOrErr for Vec<i8> {
        fn pop_or_err(&mut self) -> Result<i8, String> {
            self.pop().ok_or_else(|| "stack empty".to_owned())
        }
    }
    

    我试过:

    trait PopOrErr<T> {
        fn pop_or_err(&mut self) -> Result<T, String>;
    }
    
    impl PopOrErr<T> for Vec<T> {
        fn pop_or_err(&mut self) -> Result<T, String> {
            self.pop().ok_or_else(|| "stack empty".to_owned())
        }
    }
    

    error[E0412]: cannot find type `T` in this scope
      --> src/main.rs:29:15
       |
    29 | impl PopOrErr<T> for Vec<T> {
       |     -         ^ not found in this scope
       |     |
       |     help: you might be missing a type parameter: `<T>`
    
    error[E0412]: cannot find type `T` in this scope
      --> src/main.rs:29:26
       |
    29 | impl PopOrErr<T> for Vec<T> {
       |     -                    ^ not found in this scope
       |     |
       |     help: you might be missing a type parameter: `<T>`
    
    error[E0412]: cannot find type `T` in this scope
      --> src/main.rs:30:40
       |
    29 | impl PopOrErr<T> for Vec<T> {
       |     - help: you might be missing a type parameter: `<T>`
    30 |     fn pop_or_err(&mut self) -> Result<T, String> {
       |                                        ^ not found in this scope
    

    我该怎么做 PopOrErr 包含的类型的泛型 在内部 向量?

    1 回复  |  直到 3 年前
        1
  •  1
  •   nlta    3 年前

    “您可能缺少一个类型参数: <T> “编译器正在尝试提供帮助。请将 <T> 上面写着,你很乐意去。

    trait PopOrErr<T> {
        fn pop_or_err(&mut self) -> Result<T, String>;
    }
    
    // Add it here: impl<T>
    impl<T> PopOrErr<T> for Vec<T> {
        fn pop_or_err(&mut self) -> Result<T, String> {
            self.pop().ok_or("stack empty".to_string())
        }
    }
    

    您在ok_或_中有一个不相关的错误,我将其替换为 ok_or 在上面

    如果你想知道为什么你需要把通用的 impl 以及 fn this question