I need to write a function that takes a string as an input, splits it by the line break character and trims all the redundant break characters in each entry of the split. I’ve come up with the following:
fn split_and_trim(text: &String) {
let lines - text.split('\n').map(|l| String::from(l).trim());
println!("{:?}", lines)
}
But this code returns me the following error:
6 | let lines = text.map(|l| String::from(l).trim());
| ---------------^^^^^^^
| |
| returns a reference to data owned by the current function
| temporary value created here
Trying to rewrite it the following way:
let lines: Vec<String> = text.split('\n').map(|l| String::from(l).trim()).collect();
Returns another error:
value of type `Vec<String>` cannot be built from `std::iter::Iterator<Item=&str>`
What would be the correct way of achieving this goal (splitting the string and trimming the each element)? Thanks in advance!
>Solution :
You don’t need to create new Strings here, since trim only needs slices. (playground)
fn split_and_trim(text: &str) {
let lines: Vec<&str> = text.split('\n').map(|l| l.trim()).collect();
println!("{:?}", lines)
}
You should also take &str instead of &String as a function parameter in almost all cases.
If you need Strings, you can convert them after trimming.