简体   繁体   English

str和字符串之间不匹配

[英]mismatches between str and string

I this tiny program, but I can't make it run. 我这个小程序,但是我不能运行它。 I get type mismatches between &str and String or similar errors. 我在&strString之间发现类型不匹配或类似的错误。

So this is the program 这是程序

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);


}

I constantly get this error: 我不断收到此错误:

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![]);
                                                       ^~~~~~~~~~

I tried changing the line 我试图换线

let mut str_vec: Vec<&str> = l.split(";").collect();

to

let mut str_vec: Vec<String> = l.split(";").collect();

But I got this error: 但是我得到了这个错误:

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();

So how do I either extract String from l instead of &str ? 那么,如何从l而不是&str提取String呢? Also, if there's a better solution let me know please as my newbiness with this technology is probably apparent to all. 另外,如果有更好的解决方案,请告诉我,因为我对这项技术的新颖性可能对所有人都是显而易见的。

A more detailed answer than a comment: 比评论更详细的答案:

The reason your example fails to compile initially is because you are trying to insert a slice into a vector of Strings. 您的示例最初无法编译的原因是,您正在尝试将切片插入Strings向量中。 Because the primitive type str implements the ToString trait, you can call the to_string() method to convert it to a String giving your vector the correct type. 因为原始类型str实现了ToString特征,所以您可以调用to_string()方法将其转换为String,从而为您的向量提供正确的类型。

Another option would be to_owned() as illustrated in this thread. 线程所示,另一个选项是to_owned()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM