Consider this Rust code snippet. What will it print when run?
fn main() {
let x = 5;
let y = { let x = 3; x + 1 };
println!("{}", x + y);
}Remember that inner blocks can shadow outer variables temporarily.
The inner block defines a new x as 3, then adds 1, so y is 4. The outer x is 5. So the sum is 5 + 4 = 9.
Wait, option C says 8, option C says 9. Let's check carefully.
Inner block: let x = 3; x + 1 evaluates to 4.
Outer x is 5.
Sum: 5 + 4 = 9.
Option C is 9, option C is 8. So correct answer is A.
What error will this Rust code cause when compiled?
fn main() {
let mut x = 10;
let y = &x;
x = 20;
println!("{}", y);
}Rust enforces borrowing rules at compile time.
The variable x is borrowed immutably by y. Then x is assigned a new value while the borrow is active, which is not allowed. This causes a compile-time error.
Which of the following correctly lists the main steps Rust compiler performs in order?
Think about how source code is processed from raw text to machine code.
Rust compiler first breaks code into tokens (lexical analysis), then builds a syntax tree (parsing), then checks borrow rules (borrow checking), and finally generates machine code (code generation).
Examine this Rust code. Why does it panic when run?
fn main() {
let v = vec![1, 2, 3];
let x = v[3];
println!("{}", x);
}Check the vector length and the index used.
The vector has elements at indices 0, 1, and 2. Accessing index 3 is out of bounds, causing a runtime panic.
Consider this Rust async code using tokio. What will it print?
#[tokio::main]
async fn main() {
let handle = tokio::spawn(async {
5 + 3
});
let result = handle.await.unwrap();
println!("{}", result);
}Think about what tokio::spawn returns and how await works.
The spawned task returns 8. Awaiting the handle unwraps the result and prints 8.