Consider the following Rust program. What will it print?
fn main() {
let a = true;
let b = false;
println!("{}", a && b || !b);
}Remember the precedence of logical operators: ! has highest, then &&, then ||.
The expression a && b || !b evaluates as (a && b) || (!b). Since a is true and b is false, a && b is false. !b is true. So the whole expression is false || true, which is true.
Look at this Rust code snippet. What is the value of x after execution?
fn main() {
let x = if true { 10 } else { 20 };
println!("{}", x);
}The if expression returns the value of the branch taken.
Since the condition is true, the if expression returns 10. So x is 10.
Analyze this Rust code and choose the output it produces.
fn main() {
let a = true;
let b = false;
let c = a ^ b;
println!("{}", c);
}The ^ operator on booleans means XOR (exclusive or).
True XOR False is True, so c is true.
What error will this Rust code cause when compiled?
fn main() {
let x: bool = 1;
println!("{}", x);
}Rust is strict about types and does not allow implicit conversion from integers to booleans.
The line let x: bool = 1; tries to assign an integer to a boolean variable. Rust does not allow this, so it causes a type mismatch compilation error.
Consider this Rust code that filters a vector of booleans. How many items remain after filtering?
fn main() {
let values = vec![true, false, true, false, false, true];
let filtered: Vec<bool> = values.into_iter().filter(|&x| x).collect();
println!("{}", filtered.len());
}The filter keeps only true values.
The vector has 3 true values. The filter keeps only those, so the length is 3.