Consider the following Rust code that defines a struct and accesses its fields. What will be printed?
struct Point {
x: i32,
y: i32,
}
fn main() {
let p = Point { x: 10, y: 20 };
println!("x: {}, y: {}", p.x, p.y);
}Remember how struct fields are accessed in Rust using dot notation.
The struct Point has fields x and y. The instance p is created with x=10 and y=20. Accessing p.x and p.y prints those values.
Given this Rust code with a tuple struct, what will be the output?
struct Color(u8, u8, u8);
fn main() {
let black = Color(0, 0, 0);
println!("Red: {}, Green: {}, Blue: {}", black.0, black.1, black.2);
}Tuple struct fields are accessed by dot and index starting at zero.
The tuple struct Color has three fields accessed as .0, .1, and .2. The instance black has all zeros, so the output prints zeros.
Examine the code below. Why does it fail to compile?
mod shapes {
pub struct Rectangle {
width: u32,
pub height: u32,
}
}
fn main() {
let rect = shapes::Rectangle { width: 30, height: 50 };
println!("Width: {}, Height: {}", rect.width, rect.height);
}Check the visibility of struct fields and how Rust enforces privacy.
The field width is private (no pub), so it cannot be accessed outside the shapes module. The code tries to access rect.width in main, causing a compile error.
Given these structs, which code correctly prints the city name?
struct Address {
city: String,
}
struct Person {
name: String,
address: Address,
}
fn main() {
let person = Person {
name: String::from("Alice"),
address: Address { city: String::from("Paris") },
};
// Which line correctly prints the city?
}Use dot notation to access nested struct fields in Rust.
Rust uses dot notation to access fields. person.address.city accesses the city field inside the address field of person. The other options use invalid syntax.
Consider this Rust code that mutates a struct field. How many fields does the struct instance have after mutation?
struct Config {
debug: bool,
version: u8,
}
fn main() {
let mut cfg = Config { debug: false, version: 1 };
cfg.debug = true;
// How many fields does cfg have now?
}Mutating a field does not change the number of fields in a struct.
The struct Config has two fields: debug and version. Changing the value of debug does not remove or add fields. The instance still has 2 fields.
