Rust how to convert vector of raw strings to struct String


#1

I need to store strings in a struct. I can do this by defining a vector:

struct A {
    strings: Vec<String>,
}

Later during runtime I need to read config file and to parse strings from there:

fn read_config() {
    // reading config here..
    for (k, v) in config {
        let cfg_strings = v.split_whitespace().collect(); // this gives me Vec<&str>
        let a = A { strings: cfg_strings }; // ???
    }
}

So I need to convert Vec<&str> to Vec<String>.
The easiest way I think is to do this:

let cfg_strings: Vec<&str> = ...;
let mut string_vec: Vec<String> = Vec::new();
for s in &cfg_strings {
    strings_vec.push(s.to_string());
}

Is there any better way to do this?


#2

You can use map function, like this:

v.split_whitespace().map(|s| s.to_string()).collect();

#3

Alternatively you can use this version:

v.split_whitespace().map(String::from).collect()

Which I prefer to use whenever I can to get rid of the closure (It’s just a syntactical preference, no speedup or anything)


#4

Your code does not work.

error: the trait bound &std::collections::HashMap<std::string::String, std::string::String>: std::iter::FromIterator<std::string::String> is not satisfied [E0277]
/bot.rs:135 maps = v.split_whitespace().map(String::from).collect();

Am I doing something wrong?


#5

That’s because your left hand side is a HashMap and it doesn’t know how to insert single strings into a HashMap.