Bird
Raised Fist0
Rustprogramming~20 mins

Accessing fields in Rust - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Rust Field Access Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this Rust code accessing struct fields?

Consider the following Rust code that defines a struct and accesses its fields. What will be printed?

Rust
struct Point {
    x: i32,
    y: i32,
}

fn main() {
    let p = Point { x: 10, y: 20 };
    println!("x: {}, y: {}", p.x, p.y);
}
ACompilation error: cannot access fields directly
Bx: 20, y: 10
Cx: 10, y: 20
Dx: 0, y: 0
Attempts:
2 left
💡 Hint

Remember how struct fields are accessed in Rust using dot notation.

❓ Predict Output
intermediate
2:00remaining
What happens when accessing a field of a tuple struct?

Given this Rust code with a tuple struct, what will be the output?

Rust
struct Color(u8, u8, u8);

fn main() {
    let black = Color(0, 0, 0);
    println!("Red: {}, Green: {}, Blue: {}", black.0, black.1, black.2);
}
ARed: 0, Green: 0, Blue: 0
BRed: 1, Green: 1, Blue: 1
CCompilation error: tuple struct fields cannot be accessed by index
DRuntime error: index out of bounds
Attempts:
2 left
💡 Hint

Tuple struct fields are accessed by dot and index starting at zero.

🔧 Debug
advanced
2:00remaining
Why does this code fail to compile when accessing a private field?

Examine the code below. Why does it fail to compile?

Rust
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);
}
AError because struct Rectangle is private
BError because field 'width' is private and cannot be accessed outside the module
CError because height field is not initialized
DNo error, prints Width: 30, Height: 50
Attempts:
2 left
💡 Hint

Check the visibility of struct fields and how Rust enforces privacy.

📝 Syntax
advanced
2:00remaining
Which option correctly accesses a nested struct field?

Given these structs, which code correctly prints the city name?

Rust
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?
}
Aprintln!("City: {}", person.address.city);
Bprintln!("City: {}", person.address["city"]);
Cprintln!("City: {}", person.city.address);
Dprintln!("City: {}", person["address"].city);
Attempts:
2 left
💡 Hint

Use dot notation to access nested struct fields in Rust.

🚀 Application
expert
2:00remaining
How many fields does this struct instance have after mutation?

Consider this Rust code that mutates a struct field. How many fields does the struct instance have after mutation?

Rust
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?
}
A1
BCompilation error due to mutation
C0
D2
Attempts:
2 left
💡 Hint

Mutating a field does not change the number of fields in a struct.

Practice

(1/5)
1. In Rust, how do you access the field age of a struct instance named person?
easy
A. person::age
B. person->age
C. person["age"]
D. person.age

Solution

  1. Step 1: Understand struct field access syntax

    In Rust, fields of a struct instance are accessed using the dot (.) operator.
  2. Step 2: Apply the dot operator to the instance and field

    Given the instance person and field age, the correct syntax is person.age.
  3. Final Answer:

    person.age -> Option D
  4. Quick Check:

    Use dot (.) to access fields [OK]
Hint: Use dot (.) to access struct fields quickly [OK]
Common Mistakes:
  • Using arrow (->) like in C/C++
  • Trying to access fields like dictionary keys
  • Using double colon (::) which is for paths
2. Which of the following is the correct way to define a struct and access its field color in Rust?
easy
A. struct Car { color: String } let my_car = Car { color: "red" }; println!("{}", my_car["color"]);
B. struct Car { color: String } let my_car = Car { color: "red" }; println!("{}", my_car->color);
C. struct Car { color: String } let my_car = Car { color: String::from("red") }; println!("{}", my_car.color);
D. struct Car { color: String } let my_car = Car { color: String::from("red") }; println!("{}", Car.color);

Solution

  1. Step 1: Check struct definition and instance creation

    The struct Car is correctly defined with a field color of type String. The instance my_car is created with color: String::from("red"), which is correct.
  2. Step 2: Verify field access syntax

    The field is accessed using my_car.color, which is the correct way to access struct fields in Rust.
  3. Final Answer:

    struct Car { color: String } let my_car = Car { color: String::from("red") }; println!("{}", my_car.color); -> Option C
  4. Quick Check:

    Struct fields accessed with dot and proper String initialization [OK]
Hint: Use String::from for strings and dot for fields [OK]
Common Mistakes:
  • Using arrow (->) instead of dot (.)
  • Trying to access fields like dictionary keys
  • Using struct name instead of instance to access fields
3. What will be the output of this Rust code?
struct Point { x: i32, y: i32 }
fn main() {
    let p = Point { x: 10, y: 20 };
    println!("{}", p.x + p.y);
}
medium
A. 30
B. 1020
C. x y
D. Compilation error

Solution

  1. Step 1: Understand struct and instance values

    The struct Point has fields x and y with values 10 and 20 respectively.
  2. Step 2: Calculate the sum of fields

    The code prints the sum of p.x and p.y, which is 10 + 20 = 30.
  3. Final Answer:

    30 -> Option A
  4. Quick Check:

    Sum of fields x and y = 30 [OK]
Hint: Add numeric fields accessed by dot to get sum [OK]
Common Mistakes:
  • Concatenating numbers as strings
  • Using wrong field names
  • Expecting compilation error due to field access
4. Identify the error in this Rust code snippet:
struct User { name: String, age: u32 }
fn main() {
    let user = User { name: String::from("Alice"), age: 30 };
    println!("{}", user->name);
}
medium
A. Using arrow (->) instead of dot (.) to access field
B. Missing semicolon after struct definition
C. Incorrect type for age field
D. String::from used incorrectly

Solution

  1. Step 1: Check field access syntax

    The code uses user->name which is invalid in Rust. Rust uses dot (.) to access fields.
  2. Step 2: Confirm other parts are correct

    The struct definition, instance creation, and String::from usage are all correct.
  3. Final Answer:

    Using arrow (->) instead of dot (.) to access field -> Option A
  4. Quick Check:

    Use dot (.) not arrow (->) for fields [OK]
Hint: Remember Rust uses dot (.) for fields, not arrow (->) [OK]
Common Mistakes:
  • Confusing Rust with C/C++ pointer syntax
  • Thinking arrow works for references
  • Ignoring compiler error messages
5. Given this struct and code, what is the output?
struct Product { name: String, price: f64, discount: Option<f64> }

fn main() {
    let p = Product { name: String::from("Book"), price: 30.0, discount: Some(5.0) };
    let final_price = match p.discount {
        Some(d) => p.price - d,
        None => p.price,
    };
    println!("{} costs ${}", p.name, final_price);
}
hard
A. Book costs $35
B. Book costs $25
C. Book costs $30
D. Compilation error due to Option usage

Solution

  1. Step 1: Understand struct and field values

    The Product instance p has price 30.0 and discount Some(5.0).
  2. Step 2: Calculate final price using match on Option

    The match extracts discount value 5.0 and subtracts it from price: 30.0 - 5.0 = 25.0.
  3. Step 3: Print output with name and final price

    The output string is Book costs $25.
  4. Final Answer:

    Book costs $25 -> Option B
  5. Quick Check:

    Option unwrap and arithmetic produce 25 [OK]
Hint: Use match to handle Option fields safely [OK]
Common Mistakes:
  • Ignoring Option and causing runtime panic
  • Using None branch incorrectly
  • Confusing price and discount arithmetic
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard