Consider the following Rust code using tuples. What will it print?
fn main() {
let tup: (i32, f64, u8) = (500, 6.4, 1);
let (x, y, z) = tup;
println!("{} {} {}", x, y, z);
}Remember tuple elements keep their order and types.
The tuple tup has elements in order: 500 (i32), 6.4 (f64), and 1 (u8). The pattern (x, y, z) matches them in order. So printing x y z prints 500 6.4 1.
What will this Rust program print?
fn main() {
let arr = [10, 20, 30, 40, 50];
let slice = &arr[1..4];
println!("{:?}", slice);
}Remember Rust slices include the start index but exclude the end index.
The slice &arr[1..4] includes elements at indices 1, 2, and 3, which are 20, 30, 40. The end index 4 is excluded.
Look at this Rust code defining and using a struct. Why does it fail to compile?
struct Point {
x: i32,
y: i32,
}
fn main() {
let p = Point { x: 5 };
println!("({}, {})", p.x, p.y);
}Check if all struct fields are initialized when creating an instance.
The struct Point has two fields: x and y. When creating p, only x is given a value. Rust requires all fields to be initialized unless default values or other constructors are used.
What will this Rust program print?
enum Message { Quit, Move { x: i32, y: i32 }, Write(String), } fn main() { let msg = Message::Move { x: 10, y: 20 }; match msg { Message::Quit => println!("Quit message"), Message::Move { x, y } => println!("Move to ({}, {})", x, y), Message::Write(text) => println!("Write message: {}", text), } }
Look at which enum variant is created and matched.
The variable msg is created as Message::Move { x: 10, y: 20 }. The match arm for Message::Move prints Move to (10, 20). Other arms do not run.
Consider this nested tuple in Rust:
let nested = ((1, 2), (3, (4, 5)));
How many individual integer elements does nested contain?
Count all integers inside all inner tuples.
The tuple nested contains two elements: (1, 2) and (3, (4, 5)). The first inner tuple has 2 integers, the second has 1 integer and another tuple with 2 integers. Total is 2 + 1 + 2 = 5 integers.