Rust how to convert vector of raw strings to struct String


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 {

Is there any better way to do this?


You can use map function, like this:

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


Alternatively you can use this version:


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


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]
/ maps = v.split_whitespace().map(String::from).collect();

Am I doing something wrong?


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