I’m confused with something that should be very simple. I have a function that takes user input, splits it into vector by spaces and return ssaid vector:
fn get_rotors() -> Vec<&'static str> {
let mut foo: String = String::new(); # compiler says "foo" is borrowed from here
println!("Enter a set of 3 Roman numerals separated by spaces.
\nFor example: I IV VI");
let mut ids_input: String = String::new();
match stdin().read_line(&mut ids_input) {
Ok(n) => foo = n.to_string().clone(),
Err(_Error) => foo = "".to_string(),
};
let rotor_vec: Vec<_> = foo.split(" ").collect();
return rotor_vec
}
In this version I get a compiler error that I can’t return a value owned by the function.
I thought that maybe I should try and dereference it:
--snip--
return *rotor_vec
But here I get: expected struct Vec<&'static str> found slice [&str].
Ok, says I, I’ll try explicitly converting it to vector when returning:
--snip--
return *rotor_vec.to_vec()
Same result.
I tried using clone(), which also didn’t work, so I can’t seem to return value from function and I have no idea why it is so.
>Solution :
Your function claims to return a vector of string slices that live forever (&'static str). But you actually return a vector of string slices that point into the local foo variable, which goes out of scope as the function leaves, so those slices would dangle.
What you really want is to return a Vec<String>. Which means that after the split, you need to turn each slice into an owned string with to_owned.