Bird
Raised Fist0
Rustprogramming~20 mins

Defining structs in Rust - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Rust Struct 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 struct code?

Consider this Rust code defining a struct and printing a field:

struct Person {
    name: String,
    age: u8,
}

fn main() {
    let p = Person { name: String::from("Alice"), age: 30 };
    println!("{} is {} years old.", p.name, p.age);
}

What will this program print?

Rust
struct Person {
    name: String,
    age: u8,
}

fn main() {
    let p = Person { name: String::from("Alice"), age: 30 };
    println!("{} is {} years old.", p.name, p.age);
}
AAlice is 30 years old.
BPerson { name: "Alice", age: 30 }
C30 is Alice years old.
DCompilation error due to missing semicolon
Attempts:
2 left
💡 Hint

Look at how the println! macro uses the fields.

❓ Predict Output
intermediate
2:00remaining
What error does this Rust struct code produce?

Examine this Rust code:

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

fn main() {
    let p = Point { x: 5 };
    println!("({}, {})", p.x, p.y);
}

What error will the compiler show?

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

fn main() {
    let p = Point { x: 5 };
    println!("({}, {})", p.x, p.y);
}
Aerror: cannot find value `y` in this scope
Berror: missing field `y` in initializer of `Point`
Cerror: expected `;` after struct definition
DNo error, prints (5, 0)
Attempts:
2 left
💡 Hint

Check if all fields are initialized when creating a struct instance.

🔧 Debug
advanced
2:00remaining
Why does this Rust struct code fail to compile?

Look at this Rust code:

struct Rectangle {
    width: u32,
    height: u32,
}

fn main() {
    let rect = Rectangle { width: 30, height: 50 };
    println!("The area is {}", rect.area());
}

impl Rectangle {
    fn area(&self) -> u32 {
        self.width * self.height
    }
}

Why does this code fail to compile?

Rust
struct Rectangle {
    width: u32,
    height: u32,
}

fn main() {
    let rect = Rectangle { width: 30, height: 50 };
    println!("The area is {}", rect.area());
}

impl Rectangle {
    fn area(&self) -> u32 {
        self.width * self.height
    }
}
ANo error, prints: The area is 1500
Berror: method `area` not found for struct `Rectangle`
Cerror: missing `impl` block for Rectangle
Derror: cannot call method on `rect` because it is not mutable
Attempts:
2 left
💡 Hint

Check if methods can be called on immutable instances.

📝 Syntax
advanced
2:00remaining
Which option correctly defines a tuple struct in Rust?

Which of these options correctly defines a tuple struct named Color with three u8 fields?

Astruct Color = (u8, u8, u8);
Bstruct Color { u8, u8, u8 };
Cstruct Color(u8, u8, u8);
Dstruct Color(u8 u8 u8);
Attempts:
2 left
💡 Hint

Tuple structs use parentheses with types inside.

🚀 Application
expert
3:00remaining
How many fields does this Rust struct instance have after update?

Given this Rust code:

struct User {
    username: String,
    email: String,
    active: bool,
    sign_in_count: u64,
}

fn main() {
    let mut user1 = User {
        email: String::from("user@example.com"),
        username: String::from("user123"),
        active: true,
        sign_in_count: 1,
    };

    let user2 = User {
        email: String::from("new@example.com"),
        ..user1
    };

    println!("User2 username: {}", user2.username);
}

How many fields does user2 have and what is its username value?

Rust
struct User {
    username: String,
    email: String,
    active: bool,
    sign_in_count: u64,
}

fn main() {
    let mut user1 = User {
        email: String::from("user@example.com"),
        username: String::from("user123"),
        active: true,
        sign_in_count: 1,
    };

    let user2 = User {
        email: String::from("new@example.com"),
        ..user1
    };

    println!("User2 username: {}", user2.username);
}
ACompilation error due to move of user1
B4 fields; username is "new@example.com"
C2 fields; username is "user123"
D4 fields; username is "user123"
Attempts:
2 left
💡 Hint

Remember that struct update syntax copies remaining fields.

Practice

(1/5)
1. What is the purpose of defining a struct in Rust?
easy
A. To write a loop
B. To create a new function
C. To handle errors
D. To group related data together under one name

Solution

  1. Step 1: Understand what a struct represents

    A struct is used to group related pieces of data together, like a blueprint for an object.
  2. Step 2: Compare options to the definition

    Only To group related data together under one name correctly describes grouping related data under one name, which is the purpose of a struct.
  3. Final Answer:

    To group related data together under one name -> Option D
  4. Quick Check:

    Struct groups data = C [OK]
Hint: Structs group data fields under one name [OK]
Common Mistakes:
  • Thinking structs define functions
  • Confusing structs with loops
  • Assuming structs handle errors
2. Which of the following is the correct way to define a struct named Person with fields name (string) and age (u32)?
easy
A. struct Person { name: String, age: u32 }
B. struct Person(name: String, age: u32);
C. Person struct { name: String; age: u32 }
D. struct Person { name String, age u32 }

Solution

  1. Step 1: Recall Rust struct syntax

    Rust structs use the syntax: struct Name { field1: Type1, field2: Type2 } with commas and colons.
  2. Step 2: Check each option

    struct Person { name: String, age: u32 } matches correct syntax with colons and commas. Options A, B, and C have syntax errors like missing colons, wrong punctuation, or wrong order.
  3. Final Answer:

    struct Person { name: String, age: u32 } -> Option A
  4. Quick Check:

    Correct struct syntax uses colons and commas = D [OK]
Hint: Use colons and commas inside braces for struct fields [OK]
Common Mistakes:
  • Omitting colons between field names and types
  • Using semicolons instead of commas
  • Wrong order of keywords
3. What will be the output of this Rust code?
struct Point { x: i32, y: i32 }

fn main() {
    let p = Point { x: 5, y: 10 };
    println!("({}, {})", p.x, p.y);
}
medium
A. Point { x: 5, y: 10 }
B. (10, 5)
C. (5, 10)
D. Compilation error

Solution

  1. Step 1: Understand struct initialization and field access

    The struct Point is created with x=5 and y=10. Accessing p.x and p.y prints these values.
  2. Step 2: Analyze the println! macro

    The format string "({}, {})" prints the two values separated by a comma and space, so output is (5, 10).
  3. Final Answer:

    (5, 10) -> Option C
  4. Quick Check:

    Print fields x=5, y=10 as (5, 10) [OK]
Hint: Print struct fields by accessing them with dot notation [OK]
Common Mistakes:
  • Mixing up field values order
  • Expecting debug print without implementing Debug trait
  • Assuming struct prints automatically
4. Identify the error in this struct definition:
struct Car {
    model String,
    year: u32,
}
medium
A. Missing colon between field name and type for model
B. Missing semicolon after struct
C. Extra comma after last field
D. Incorrect struct keyword

Solution

  1. Step 1: Check field syntax

    Each field must have a colon between the name and type. Here, model String misses the colon.
  2. Step 2: Verify other parts

    Commas after fields are allowed, no semicolon needed after struct, and struct keyword is correct.
  3. Final Answer:

    Missing colon between field name and type for model -> Option A
  4. Quick Check:

    Field syntax requires colon = B [OK]
Hint: Field name and type must be separated by a colon [OK]
Common Mistakes:
  • Omitting colon between field and type
  • Thinking semicolon needed after struct
  • Removing commas after fields
5. You want to define a struct Book with fields title (String), author (String), and pages (u32). Then create an instance with title "Rust Guide", author "Alice", and pages 250. Which code correctly does this?
hard
A. struct Book(title: String, author: String, pages: u32); let my_book = Book("Rust Guide", "Alice", 250);
B. struct Book { title: String, author: String, pages: u32 } let my_book = Book { title: "Rust Guide".to_string(), author: "Alice".to_string(), pages: 250 };
C. struct Book { title String, author String, pages u32 } let my_book = Book { title: "Rust Guide", author: "Alice", pages: 250 };
D. struct Book { title: String, author: String, pages: u32 } let my_book = Book { title: "Rust Guide", author: "Alice", pages: "250" };

Solution

  1. Step 1: Check struct definition syntax

    struct Book { title: String, author: String, pages: u32 } let my_book = Book { title: "Rust Guide".to_string(), author: "Alice".to_string(), pages: 250 }; correctly defines the struct with colons and commas. struct Book(title: String, author: String, pages: u32); let my_book = Book("Rust Guide", "Alice", 250); uses tuple struct syntax incorrectly for this case. struct Book { title String, author String, pages u32 } let my_book = Book { title: "Rust Guide", author: "Alice", pages: 250 }; misses colons. struct Book { title: String, author: String, pages: u32 } let my_book = Book { title: "Rust Guide", author: "Alice", pages: "250" }; uses a string for pages which should be u32.
  2. Step 2: Check instance creation

    struct Book { title: String, author: String, pages: u32 } let my_book = Book { title: "Rust Guide".to_string(), author: "Alice".to_string(), pages: 250 }; converts string literals to String with to_string(), which is required. struct Book(title: String, author: String, pages: u32); let my_book = Book("Rust Guide", "Alice", 250); uses tuple struct syntax incorrectly. struct Book { title: String, author: String, pages: u32 } let my_book = Book { title: "Rust Guide", author: "Alice", pages: "250" }; uses wrong type for pages.
  3. Final Answer:

    struct Book { title: String, author: String, pages: u32 } let my_book = Book { title: "Rust Guide".to_string(), author: "Alice".to_string(), pages: 250 }; -> Option B
  4. Quick Check:

    Struct fields need colons and correct types = A [OK]
Hint: Use colons for fields and convert literals to String [OK]
Common Mistakes:
  • Using tuple struct syntax instead of named fields
  • Omitting colons in struct fields
  • Assigning wrong types to fields
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