Rust 通过迭代hashmap创建向量
在Rust中,迭代Rust 通过迭代hashmap创建向量,rust,Rust,在Rust中,迭代HashMap并将结果收集到Vec中的可选方法是什么?这是我迄今为止的尝试: use std::collections::HashMap; struct User { reference: String, email: String } fn main() { let mut users: HashMap<String, User> = HashMap::new(); users.insert("first".to_string
HashMap
并将结果收集到Vec
中的可选方法是什么?这是我迄今为止的尝试:
use std::collections::HashMap;
struct User {
reference: String,
email: String
}
fn main() {
let mut users: HashMap<String, User> = HashMap::new();
users.insert("first".to_string(), User { reference: "ref1".to_string(), email: "test@test.com".to_string() });
users.insert("second".to_string(), User { reference: "ref2".to_string(), email: "test1@test.com".to_string() });
users.insert("third".to_string(), User { reference: "ref3".to_string(), email: "test3@test.com".to_string() });
//this is my failed attempt
let user_refs: Vec<String> = users.iter().map(|(_, user)| &user.reference.clone()).collect();
}
使用std::collections::HashMap;
结构用户{
参考:字符串,
电子邮件:String
}
fn main(){
让mut用户:HashMap=HashMap::new();
users.insert(“first.”to_string(),用户{引用:“ref1”)。to_string(),电子邮件:test@test.com“.to_string()});
users.insert(“second.”to_string(),User{reference:“ref2.”to_string(),email:test1@test.com“.to_string()});
users.insert(“third.”to_string(),User{reference:“ref3”)。to_string(),email:test3@test.com“.to_string()});
//这是我失败的尝试
让user|refs:Vec=users.iter().map(|(|,user)|和user.reference.clone()).collect();
}
抛出错误
src/main.rs:15:85: 15:94 error: the trait `core::iter::FromIterator<&collections::string::String>` is not implemented for the type `collections::vec::Vec<collections::string::String>` [E0277]
src/main.rs:15 let user_refs: Vec<String> = users.iter().map(|(_, user)| &user.reference.clone()).collect();
^~~~~~~~~
src/main.rs:15:85: 15:94 note: a collection of type `collections::vec::Vec<collections::string::String>` cannot be built from an iterator over elements of type `&collections::string::String`
src/main.rs:15 let user_refs: Vec<String> = users.iter().map(|(_, user)| &user.reference.clone()).collect();
^~~~~~~~~
error: aborting due to previous error
src/main.rs:15:85:15:94错误:未为类型`collections::vec::vec`[E0277]实现特性`core::iter::FromIterator`
src/main.rs:15 let user_refs:Vec=users.iter().map(|(|,user)|&user.reference.clone()).collect();
^~~~~~~~~
src/main.rs:15:85:15:94注意:不能通过迭代器在`&collections::string::string`类型的元素上构建`collections::vec::vec`类型的集合`
src/main.rs:15 let user_refs:Vec=users.iter().map(|(|,user)|&user.reference.clone()).collect();
^~~~~~~~~
错误:由于上一个错误而中止
生成的Vec需要拥有字符串,因此在user.reference.clone()之前删除&
游乐场网址:
要点URL:不要使用to_string()
将&str
转换为字符串
,因为它贯穿整个std::fmt
机器。当可以从上下文推断出字符串
目标类型时,您可能希望使用to()
,否则使用to_owned()
。