Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Map the split to trim each entry

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading