我有一個作業特點:
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型別進行通用化?
uj5u.com熱心網友回復:
“您可能缺少型別引數:<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查看這個問題
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/412126.html
標籤:
上一篇:使用泛型回傳函式的方法
