[英]How to make a trait into a generic on Vec<T>?
I have a working trait:我有一个工作特点:
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())
}
}
I've tried:我试过了:
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())
}
}
but it gives me:但它给了我:
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
How can I make PopOrErr
generic on the type contained within the vector?如何在向量中包含的类型上使
PopOrErr
泛型?
"You might be missing a type parameter: <T>
" the compiler is trying to help. “您可能缺少类型参数:
<T>
”编译器试图提供帮助。 Put <T>
where it says and you are good to go.把
<T>
放在它说的地方,你对 go 很好。
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())
}
}
You have an unrelated error with ok_or_else which I replaced with ok_or
above.你有一个与 ok_or_else 无关的错误,我用上面的
ok_or
替换了它。
If you're curious as to why you need to put the generic with impl
as well as fn
check out this question如果您对为什么需要将泛型与
impl
和fn
一起使用感到好奇,请查看此问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.