2

Disclaimer: Learning Rust.

I have the following function:

fn log_action(log_file: &String, transferred_files_count: &i32) -> Result<()> {
    let mut lines = Vec::new();
    let count_as_string = transferred_files_count.to_string();
    lines.push(&count_as_string); // error
    append_lines_to_file(log_file, &lines)?;
    Ok(())
}

When trying to push &count_as_string into the vector, I get the error borrowed value does not live long enough. By accident, I noticed when I swap the two top lines, the error disappears:

fn log_action(log_file: &String, transferred_files_count: &i32) -> Result<()> {
    let count_as_string = transferred_files_count.to_string();
    let mut lines = Vec::new();
    lines.push(&count_as_string); // no error!
    append_lines_to_file(log_file, &lines)?;
    Ok(())
}

I am confused, in my opinion the order of those two lines should be irrelevant. Can someone explain the logic here?

hannu40k
  • 512
  • 1
  • 8
  • 20
  • 2
    You may also be interested in [Why is it discouraged to accept a reference to a String (&String), Vec (&Vec) or Box (&Box) as a function argument?](https://stackoverflow.com/q/40006219/155423) – Shepmaster Sep 16 '18 at 17:01
  • Great tip, thanks! – hannu40k Sep 16 '18 at 20:57

0 Answers0