Complete the code to read a number from the user and print it.
fn main() {
let mut input = String::new();
std::io::stdin().read_line(&mut [1]).expect("Failed to read line");
println!("You entered: {}", input.trim());
}The variable input is used to store the user input. We must pass it to read_line to fill it with the input data.
Complete the code to convert the input string to an integer.
fn main() {
let mut input = String::new();
std::io::stdin().read_line(&mut input).expect("Failed to read line");
let number: i32 = [1].trim().parse().expect("Please type a number!");
println!("Number is: {}", number);
}The variable input holds the string read from the user. We trim and parse it to convert to an integer.
Fix the error in the code to print the sum of two numbers read from input.
fn main() {
let mut input1 = String::new();
let mut input2 = String::new();
std::io::stdin().read_line(&mut input1).expect("Failed to read line");
std::io::stdin().read_line(&mut input2).expect("Failed to read line");
let num1: i32 = input1.trim().parse().expect("Not a number");
let num2: i32 = input2.trim().parse().expect("Not a number");
let sum = num1 + [1];
println!("Sum is: {}", sum);
}The sum should add num1 and num2. The blank must be filled with num2.
Fill both blanks to create a dictionary with word lengths for words longer than 3 letters.
fn main() {
let words = vec!["apple", "cat", "banana", "dog"];
let lengths: std::collections::HashMap<_, _> = words.iter()
.filter(|&&word| word.len() [1] 3)
.map(|&word| (word, word.[2]()))
.collect();
println!("{:?}", lengths);
}We filter words with length greater than 3 using word.len() > 3. Then map each word to its length using word.len().
Fill all three blanks to create a dictionary with uppercase keys and values for words longer than 4 letters.
fn main() {
let words = vec!["apple", "cat", "banana", "dog"];
let result: std::collections::HashMap<_, _> = words.iter()
.filter(|&&word| word.len() [1] 4)
.map(|&word| (word.[2](), word.[3]()))
.collect();
println!("{:?}", result);
}Filter words longer than 4 with word.len() > 4. Map keys to uppercase with word.to_uppercase() and values to strings with word.to_string().