如何将特征变成 Vec<T> 上的泛型?

How to make a trait into a generic on Vec<T>?

我有一个工作特点:

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 包含在 向量中 的类型上泛型?

“您可能缺少类型参数:<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_or_else 无关的错误,我用上面的 ok_or 替换了它。

如果您想知道为什么需要将泛型与 impl 以及 fn 放在一起,请查看