Consider the following Rust code snippet. What will it print?
fn main() {
let a = true;
let b = false;
let c = true;
if a && b || c {
println!("Result is true");
} else {
println!("Result is false");
}
}Remember the precedence of logical operators: && has higher precedence than ||.
The expression a && b || c is evaluated as (a && b) || c. Since a && b is false and c is true, the overall expression is true. So it prints "Result is true".
Analyze the following Rust code and determine its output.
fn main() {
let x = false;
let y = true;
if !x && y {
println!("Condition met");
} else {
println!("Condition not met");
}
}Negation ! flips the boolean value.
!x is true because x is false. Then true && true is true, so it prints "Condition met".
Examine this Rust code snippet. What error will it cause when compiled?
fn main() {
let a = true;
let b = false;
if a & b {
println!("True");
} else {
println!("False");
}
}In Rust, & is a bitwise operator and && is a logical operator.
The operator & is a bitwise AND and cannot be used directly on bool values in Rust. This causes a type mismatch error.
What will this Rust program print?
fn main() {
let p = false;
let q = true;
let r = false;
if p || q && r {
println!("Yes");
} else {
println!("No");
}
}Remember that && has higher precedence than ||.
The expression is evaluated as p || (q && r). Since q && r is false and p is false, the whole expression is false. So it prints "No".
After running this Rust code, what is the value of result?
fn main() {
let a = true;
let b = false;
let c = true;
let result = (a && !b) || (b && c);
println!("{}", result);
}Evaluate each part carefully using logical rules.
a && !b is true && true which is true. b && c is false && true which is false. So true || false is true.