2016-03-01 39 views
1

我这个小程序,但我不能让它运行。我得到&strString之间的类型不匹配或类似的错误。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而不是&strString?另外,如果有更好的解决方案,请让我知道,因为我对这项技术的新用途可能很明显。

+1

一个简单的解决方案是调用'str_vec [2] .to_string()'。 – squiguy

+1

令人惊叹。我建议将其作为答案,然后我可以接受它。这样你,我会得到更多的积分 –

回答

5

更详细的解答比评论:

你的榜样未能最初编译的原因是因为你试图插入一个切片成字符串的向量。由于原始类型str实现了ToString特征,因此可以调用to_string()方法将其转换为字符串,从而为您的向量提供正确的类型。

另一种选择是to_owned(),如this线程所示。

+0

我忘了谢谢你之前。非常感谢!! –

+0

不客气,快乐编码。 – squiguy

相关问题