0
0
Rustprogramming~30 mins

Handling input values in Rust - Mini Project: Build & Apply

Choose your learning style9 modes available
Handling input values
๐Ÿ“– Scenario: You are creating a simple Rust program that asks the user for their age and then tells them if they are old enough to vote.
๐ŸŽฏ Goal: Build a Rust program that reads an input value from the user, converts it to a number, and checks if the user is 18 or older.
๐Ÿ“‹ What You'll Learn
Use std::io::stdin() to read input
Convert the input string to an u32 number
Use an if statement to check the age
Print a message based on the age
๐Ÿ’ก Why This Matters
๐ŸŒ Real World
Reading and handling user input is essential for interactive programs like command-line tools and games.
๐Ÿ’ผ Career
Many programming jobs require you to safely get and use input from users or other sources.
Progress0 / 4 steps
1
Create a variable to store user input
Create a mutable variable called input of type String and initialize it with String::new().
Rust
Need a hint?

Use let mut input = String::new(); to create an empty string for input.

2
Read input from the user
Use std::io::stdin().read_line(&mut input).expect("Failed to read line") to read the user's input into the input variable.
Rust
Need a hint?

Use read_line to get input from the user and store it in input.

3
Convert input string to a number
Create a variable called age and set it to input.trim().parse::().expect("Please type a number!") to convert the input string to a number.
Rust
Need a hint?

Use trim() to remove whitespace and parse::() to convert to a number.

4
Check age and print message
Use an if statement to check if age is 18 or more. If yes, print "You are old enough to vote!". Otherwise, print "You are not old enough to vote.".
Rust
Need a hint?

Use if age >= 18 to check the age and println! to show the message.