Return truncate string

I have the following function:

fn trim_input<'a>(input: &'a str) -> &'a str {
    let len = input.trim_end_matches(&['\r', '\n'][..]).len();
    let mut literal_string = String::from(input);


let mut input = String::new();
io::stdin().read_line(&mut input)
        .expect("Not a correct input");
let trimmed_input = trim_input(input.as_str());
println!("==> {} <==", trimmed_input);

I got the following error.
--> returns a value referencing data owned by the current function

I know why I got that error but I do not know how to solve it.


Since you're creating a new string, you'll want trim_input to return a String instead of an &'a str (just change the type and remove the as_str call.

fn trim_input(input: &str) -> &str {
    input.trim_end_matches(&['\r', '\n'][..])

Can you see that there's no lifetime annotations here? Check the lifetime elision rules.


So your end-goal is to remove endline characters from the input string, right? If that's the case then isn't let trimmed_input = input.trim() sufficient?

Thank you. This is what I was looking for!