【发布时间】:2017-01-21 00:19:31
【问题描述】:
我正在尝试在 Rust 中做相当于 Ruby 的 Enumerable.collect()。
我有一个Option<Vec<Attachment>>,我想从中创建一个Option<Vec<String>>,在None guid 的情况下使用String::new() 元素。
#[derive(Debug)]
pub struct Attachment {
pub guid: Option<String>,
}
fn main() {
let ov: Option<Vec<Attachment>> =
Some(vec![Attachment { guid: Some("rere34r34r34r34".to_string()) },
Attachment { guid: Some("5345345534rtyr5345".to_string()) }]);
let foo: Option<Vec<String>> = match ov {
Some(x) => {
x.iter()
.map(|&attachment| attachment.guid.unwrap_or(String::new()))
.collect()
}
None => None,
};
}
编译器中的错误很明显:
error[E0277]: the trait bound `std::option::Option<std::vec::Vec<std::string::String>>: std::iter::FromIterator<std::string::String>` is not satisfied
--> src/main.rs:15:18
|
15 | .collect()
| ^^^^^^^ the trait `std::iter::FromIterator<std::string::String>` is not implemented for `std::option::Option<std::vec::Vec<std::string::String>>`
|
= note: a collection of type `std::option::Option<std::vec::Vec<std::string::String>>` cannot be built from an iterator over elements of type `std::string::String`
如果我记得到目前为止我从文档中读到的内容,我无法为 struct 实现我不拥有的特征。
如何使用iter().map(...).collect() 或其他方式来做到这一点?
【问题讨论】:
标签: rust