generics - expected type parameter `T`, found `&T`
问题描述
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.
解决方案
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
}
}
}
推荐阅读
- python - 如何在 django 中使用 ffmpeg 压缩 base64 解码的视频数据
- php - PHP csv 文件以列和行的形式导出
- php - Laravel 8 从旧 URL 重定向到新 URL
- python - 具有不同长度的长序列的张量流(+ keras)上的 LSTM
- angular - Angular 7 路由器有条件地过渡
- html - 如何使用 CSS 网格重新排序列?
- visual-studio-code - 如何在 Visual Studio Code 中使用相同的键开始调试 R 或 Python 代码?
- python-3.x - 在python中绘制非数值数据(分类)
- android - 使用 arraylist 从 firebase 获取数据时出错
- javascript - jQuery to Javascript/Vue