Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Rust - read STDIN - remove trailing newline (trim, chomp)

  • trim_end

  • to_owned

  • trim_end removes trailing whitespace.

  • to_owned Converts the &str to String to be able to assign to the name variable again.

use std::io;

fn main() {
    let mut name = String::new();

    println!("Please type in your name:");
    io::stdin()
        .read_line(&mut name)
        .expect("Failed to get input");

    name = name.trim_end().to_owned();

    println!("Hello {name}, how are you?");
}