Rust code analysis flashcards
For analysis code to detect errors or to understand what a piece of code does
How do you handle invalid input when parsing a string to a number in Rust?
Use match to handle Ok and Err cases from parse(). Example
match input.trim().parse::<i32>() {
Ok(num) => num,
Err(_) => {
println!("Invalid input.");
continue;
}
}</i32>
How do you define a function that takes two i32 parameters and returns an i32?
fn add(x: i32, y: i32) -> i32 {
x + y
}
What is the syntax to call a function named multiply with arguments 4 and 5?
multiply(4, 5);
How do you read a line of input from the user in Rust?
let mut input = String::new();
io::stdin().read_line(&mut input).expect(“Failed to read line”);
How do you handle input parsing errors when converting a string to an i32?
let num: i32 = match input.trim().parse() {
Ok(n) => n,
Err(_) => {
println!(“Invalid input.”);
continue;
}
};
How do you write a for loop that iterates over an array of integers?
let numbers = [1, 2, 3, 4];
for num in numbers.iter() {
println!(“{}”, num);
}
Write a while loop that runs as long as a variable count is less than 10.
let mut count = 0;
while count < 10 {
println!(“{}”, count);
count += 1;
}