我这个小程序,但我不能让它运行。我得到&str
和String
之间的类型不匹配或类似的错误。str和字符串之间的不匹配
因此,这是程序
use std::fs::File;
use std::io;
use std::io::prelude::*;
use std::io::BufReader;
use std::collections::HashMap;
fn main() {
let mut f = File::open("/home/asti/class.csv").expect("Couldn't open file");
let mut s = String::new();
let reader = BufReader::new(f);
let lines: Result<Vec<_>,_> = reader.lines().collect();
let mut class_students: HashMap<String, Vec<String>> = HashMap::new();
for l in lines.unwrap() {
let mut str_vec: Vec<&str> = l.split(";").collect();
println!("{}", str_vec[2]);
let e = class_students.entry(str_vec[2]).or_insert(vec![]);
e.push(str_vec[2]);
}
println!("{}", class_students);
}
我不断收到此错误:
hello_world.rs:20:38: 20:48 error: mismatched types:
expected `collections::string::String`,
found `&str`
(expected struct `collections::string::String`,
found &-ptr) [E0308]
hello_world.rs:20 let e = class_students.entry(str_vec[2]).or_insert(vec![]);
^~~~~~~~~~
我试图改变线路
let mut str_vec: Vec<&str> = l.split(";").collect();
到
let mut str_vec: Vec<String> = l.split(";").collect();
但我得到这个错误:
hello_world.rs:16:53: 16:60 error: the trait `core::iter::FromIterator<&str>` is not implemented for the type `collections::vec::Vec<collections::string::String>` [E0277]
hello_world.rs:16 let mut str_vec: Vec<String> = l.split(";").collect();
那么,如何既提取l
而不是&str
String
?另外,如果有更好的解决方案,请让我知道,因为我对这项技术的新用途可能很明显。
一个简单的解决方案是调用'str_vec [2] .to_string()'。 – squiguy
令人惊叹。我建议将其作为答案,然后我可以接受它。这样你,我会得到更多的积分 –