...

/

Capturing User Input

Capturing User Input

Learn how to use the terminal to ask the user to type their name and receive the result after capturing input.

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]
Hello World program for testing

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:

Press + to interact
println!("Hello, what's your name?");

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 ...