Search⌘ K
AI Features

Puzzle 2: Explanation

Explore how Rust processes string input and why using functions like trim() is essential for removing unwanted whitespace. Understand the importance of case normalization for string comparison and discover best practices to handle user input safely to prevent issues such as SQL injection. This lesson teaches fundamental techniques to write secure and effective Rust code when dealing with strings.

Test it out

Hit “Run” to see the code’s output.

use std::io::stdin;

fn main() {
    println!("What is 3+2? Type your answer and press enter.");
    let mut input = String::new();
    stdin()
        .read_line(&mut input)
        .expect("Unable to read standard input");

    if input == "5" {
        println!("Correct!");
    } else {
        println!("Incorrect!");
    }

    println!("{:#?}", input);
}
What is 3 + 2? Not 5!

Explanation

Normally, 3+2 would equal 5, but that’s not how Rust handles strings! To find out why, add the following line to the end of the program:


println!("{:#?}", input);

With this new line, we’ll be ...