Jenia Be Nice Please
Jenia Be Nice Please

Reputation: 2693

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.

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? Also, if there's a better solution let me know please as my newbiness with this technology is probably apparent to all.

Upvotes: 2

Views: 3598

Answers (1)

squiguy
squiguy

Reputation: 33380

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. 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.

Another option would be to_owned() as illustrated in this thread.

Upvotes: 5

Related Questions