Capturing User Input
Explore how to capture user input in Rust through terminal interactions. Learn to create mutable variables, use the stdin function, and apply function chaining to read data. Understand Rust's borrowing system and how to format output dynamically, enabling you to build interactive console applications.
Output text on the terminal
Most computer programs operate in a cycle of accepting input from the user and transforming that into some form of hopefully useful output.
A calculator without buttons is pretty useless, and a computer program without input is equally limited. We used println! in “Hello, world” to output text and we can use read_line() to accept data from the terminal.
We can run the following program by typing cargo run in a terminal.
[package] name = "hello" version = "0.1.0" authors = ["Your Name"] edition = "2018" # See more keys and their definitions at # https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies]
Prompting for the visitor’s name
When a visitor arrives at our fancy new treehouse, we need to ask them for their name. In Printing Text , we used println! to print text to the screen. We’ll do the same here.
Replace println!("Hello, world") with:
We replaced the output string, asking for the visitor’s name. Now we’re ready to receive and store the answer.
Storing the name in a variable
We’ll store the visitor’s name in a variable. Rust variables default as immutable. Once an immutable variable is assigned, we can’t change the value stored in the variable. We can make more variables and reference or copy a previously assigned ...