Reputation: 75
I have a generic struct, but I have a problem.
#[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
}
}
}
I get this error:
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
The edges.first() gets a reference, which causes an error.
please help me.
Upvotes: 2
Views: 2392
Reputation: 1856
You are consuming the vector and attempting to send a reference to the first element.
pub fn to_result(self) -> Option<T>{
self.edges?.into_iter().next()
}
There is no need to check if contained vector has any elements or not. You can use into_iter()
to consume the vector and send the first element if available. Playground
To make your code work, you can do the following.
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
}
}
}
Upvotes: 7