我有一个通用结构,但有一个问题。
#[derive(Debug,Clone,Serialize,Deserialize)]
pub struct Item<T> {
pub edges: Option<Vec<T>>
}
impl<T> Item<T> {
pub fn to_result(self) -> Option<T>{
match self.edges {
Some(edges) =>{
if edges.is_empty() { return None; }
return edges.first();
},
None => None
}
}
}
Run Code Online (Sandbox Code Playgroud)
我收到此错误:
expected type parameter `T`, found `&T`
note: expected enum `std::option::Option<T>`
found enum `std::option::Option<&T>`
help: type parameters must be constrained to match other types
note: for more information, visit https://doc.rust-lang.org/book/ch10-02-traits.html#traits-as-parameters
Run Code Online (Sandbox Code Playgroud)
Edges.first ()获取引用,这会导致错误。
请帮我。
您正在使用向量并尝试发送对第一个元素的引用。
pub fn to_result(self) -> Option<T>{
self.edges?.into_iter().next()
}
Run Code Online (Sandbox Code Playgroud)
不需要检查包含的向量是否有元素。您可以使用into_iter()该向量并发送第一个元素(如果可用)。操场
要使您的代码正常工作,您可以执行以下操作。
impl<T> Item<T> {
pub fn to_result(self) -> Option<T>{
match self.edges {
Some(edges) =>{
if edges.is_empty() { return None; }
return edges.into_iter().next();
},
None => None
}
}
}
Run Code Online (Sandbox Code Playgroud)