Skip to content

Instantly share code, notes, and snippets.

@mnylen
Last active August 29, 2015 14:00
Show Gist options
  • Save mnylen/399f093915aefc26dc16 to your computer and use it in GitHub Desktop.
Save mnylen/399f093915aefc26dc16 to your computer and use it in GitHub Desktop.
use std::io::BufferedReader;
use std::io;
fn main() {
let mut reader = BufferedReader::new(io::stdin());
println!("What is your name?");
let age_input: ~str = reader.read_line().unwrap();
let age_trimmed: &str = age_input.trim();
println!("Hello, {}!", age_trimmed);
}
use std::io::BufferedReader;
use std::io;
fn main() {
let mut reader = BufferedReader::new(io::stdin());
println!("What is your name?");
let age_input: &str = reader.read_line().unwrap().trim();
println!("Hello, {}!", age_input);
}
@mnylen
Copy link
Author

mnylen commented May 4, 2014

Getting this error when compiling hello_error.rs:

$ ./rustc hello_error.rs
hello_error.rs:8:27: 8:54 error: borrowed value does not live long enough
hello_error.rs:8     let age_input: &str = reader.read_line().unwrap().trim();
                                       ^~~~~~~~~~~~~~~~~~~~~~~~~~~
hello_error.rs:4:11: 11:2 note: reference must be valid for the block at 4:10...
hello_error.rs:4 fn main() {
hello_error.rs:5     let mut reader = BufferedReader::new(io::stdin());
hello_error.rs:6 
hello_error.rs:7     println!("What is your name?");
hello_error.rs:8     let age_input: &str = reader.read_line().unwrap().trim();
hello_error.rs:9 
             ...
hello_error.rs:8:9: 8:61 note: ...but borrowed value is only valid for the statement at 8:8
hello_error.rs:8     let age_input: &str = reader.read_line().unwrap().trim();
                      ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
error: aborting due to previous error

@mnylen
Copy link
Author

mnylen commented May 4, 2014

let age_input = reader.read_line().unwrap().trim is roughly equivalent to:

let age_input = {
    let tmp1 = reader.read_line();
    let tmp2 = tmp1.unwrap();

    tmp2.trim()
}
  • trim's signature is trim(&self) -> &str. Calling tmp2.trim() thus borrows tmp2.
  • the return value of trim is a reference to a substring of tmp2, which still refers the original tmp2.
  • at the end of { ... } block, the tmp2 - the original input string - gets destroyed
  • so, now that we don't have tmp2, the reference to substring to it is no longer valid and rust compiler detects this

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment