我这个小程序,但我无法让它运行。我在&str
和String
之间遇到类型不匹配或类似错误。
所以这是程序
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
中提取String
而不是&str
?另外,如果有更好的解决方案,请告诉我,因为我对这项技术的新手可能是显而易见的。
比评论更详细的答案:
您的示例最初无法编译的原因是,您尝试将切片插入到 String 向量中。由于基元类型str
实现了ToString
特征,因此可以调用 to_string()
方法将其转换为 String,从而为向量提供正确的类型。
另一个选项是to_owned()
,如此线程所示。