Rust code analysis flashcards

For analysis code to detect errors or to understand what a piece of code does

1
Q

How do you handle invalid input when parsing a string to a number in Rust?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How do you define a function that takes two i32 parameters and returns an i32?

A

fn add(x: i32, y: i32) -> i32 {
x + y
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is the syntax to call a function named multiply with arguments 4 and 5?

A

multiply(4, 5);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How do you read a line of input from the user in Rust?

A

let mut input = String::new();
io::stdin().read_line(&mut input).expect(“Failed to read line”);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How do you handle input parsing errors when converting a string to an i32?

A

let num: i32 = match input.trim().parse() {
Ok(n) => n,
Err(_) => {
println!(“Invalid input.”);
continue;
}
};

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How do you write a for loop that iterates over an array of integers?

A

let numbers = [1, 2, 3, 4];
for num in numbers.iter() {
println!(“{}”, num);
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Write a while loop that runs as long as a variable count is less than 10.

A

let mut count = 0;
while count < 10 {
println!(“{}”, count);
count += 1;
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q
A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly