Consider the following Rust code snippet. What will it print?
fn main() {
let mut x = 5;
x += 3;
x *= 2;
println!("{}", x);
}Remember that += adds and assigns, and *= multiplies and assigns.
Starting with x = 5, x += 3 makes x = 8. Then x *= 2 makes x = 16. So the output is 16.
y hold after this code?Analyze the Rust code below and determine the final value of y.
fn main() {
let mut y = 10;
y -= 4;
y /= 3;
println!("{}", y);
}Integer division truncates towards zero in Rust.
Starting with y = 10, y -= 4 makes y = 6. Then y /= 3 divides 6 by 3, resulting in 2.
Look at the Rust code below. What will it print?
fn main() {
let mut z = 0b1100u8; // binary 12
z &= 0b1010; // binary 10
z |= 0b0101; // binary 5
println!("{:b}", z);
}Apply bitwise AND then OR step by step on the binary numbers.
Start: z = 1100 (12)
After z &= 1010: z = 1000 (8)
After z |= 0101: z = 1101 (13)
Printed in binary: 1101
Examine the Rust code below. What error will it cause when compiled?
fn main() {
let x = 5;
x += 1;
println!("{}", x);
}Variables are immutable by default in Rust unless declared mut.
The variable x is not mutable, so x += 1 causes a compile-time error about assigning to an immutable variable.
a updated in this Rust code?Consider the following Rust code snippet. How many times is the variable a updated (assigned a new value) during execution?
fn main() {
let mut a = 1;
a += 2;
a *= 3;
a -= 4;
a /= 2;
a %= 3;
println!("{}", a);
}Count each assignment operator usage as one update.
The variable a is initialized once, then updated 5 times by the assignment operators: +=, *=, -=, /=, and %=. Each counts as one update.