Not quite sure how read_line() function works,

With this code:

fn main()
{
    let reader = std::io::stdin();
    let mut line = String::new();

    reader.read_line(&mut line).expect("Can't read from stdin"); // What does read_line() exactly do?

    print!("Line: {}", line);
}

I am a little confused with the read_line(&mut line) function. Why do we need a &mut before the line? The line is a variable that is not declared as a reference?

main() owns the line variable, which means that line’s memory will get cleaned up when main exits.

&mut line constructs a new mutable reference to the local variable line. A mutable reference allows code to both read and make changes to the variable being referred to (line in this case), without claiming ownership.

read_line takes a mutable reference to a String object stored elsewhere (inside main), and uses that reference to alter the String (by appending the read data). Because it doesn’t claim ownership, the altered String is still available for main to use after read_line returns.

1 Like

Ah I see, that makes sense.

If I comment out the print!("Line: {}", line) macro and change the &mut to mut, then how come I can't allow the read_line function to just take the ownership of line?

The read_line function expects a mutable reference to a string, it doesn't accept a string by value. That wouldn't make much sense anyway, as wouldn't return the string back in that case.

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.