Bird
Raised Fist0
Rustprogramming~20 mins

Creating struct instances in Rust - Practice Exercises

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 code creating a struct instance?
Consider the following Rust code that defines a struct and creates an instance. What will be printed when running this code?
Rust
struct Book {
    title: String,
    pages: u32,
}

fn main() {
    let my_book = Book {
        title: String::from("Rust Basics"),
        pages: 250,
    };
    println!("{} has {} pages", my_book.title, my_book.pages);
}
ARust Basics has pages
B250 has Rust Basics pages
CRust Basics has 250 pages
DCompilation error due to missing semicolon
Attempts:
2 left
💡 Hint
Look at how the struct fields are accessed and printed with println! macro.
❓ Predict Output
intermediate
2:00remaining
What error occurs when creating a struct instance with missing fields?
Given this Rust struct and code, what error will the compiler produce?
Rust
struct Point {
    x: i32,
    y: i32,
}

fn main() {
    let p = Point {
        x: 10,
    };
}
Aerror: missing field `y` in initializer of `Point`
Berror: expected `;` after struct initialization
Cerror: cannot find value `y` in this scope
DNo error, compiles successfully
Attempts:
2 left
💡 Hint
Rust requires all fields to be initialized unless using struct update syntax.
🔧 Debug
advanced
2:00remaining
Why does this Rust code fail to compile when creating a struct instance?
Examine the code below. Why does it fail to compile?
Rust
struct User {
    username: String,
    active: bool,
}

fn main() {
    let user1 = User {
        username: "alice",
        active: true,
    };
}
Aerror: expected struct `String`, found `&str` for field `username`
Berror: missing field `active` in initializer
Cerror: cannot assign boolean to string field
DNo error, compiles successfully
Attempts:
2 left
💡 Hint
Check the type of the value assigned to the username field.
🧠 Conceptual
advanced
2:00remaining
What does the struct update syntax do in Rust?
Given a struct instance, what is the effect of using the update syntax `..` when creating a new instance?
Rust
struct Config {
    debug: bool,
    verbose: bool,
}

fn main() {
    let default = Config { debug: false, verbose: false };
    let custom = Config { debug: true, ..default };
}
AIt merges the two structs, overwriting all fields
BIt copies all fields from `default` except those explicitly set in `custom`
CIt creates a reference to `default` inside `custom`
DIt causes a runtime error due to field duplication
Attempts:
2 left
💡 Hint
Think about how the `..` syntax helps avoid repeating field values.
❓ Predict Output
expert
2:00remaining
What is the output of this Rust code using tuple structs?
Consider the tuple struct and code below. What will be printed?
Rust
struct Color(u8, u8, u8);

fn main() {
    let black = Color(0, 0, 0);
    let white = Color(255, 255, 255);
    println!("Black: ({}, {}, {}), White: ({}, {}, {})", black.0, black.1, black.2, white.0, white.1, white.2);
}
ACompilation error: tuple struct fields accessed incorrectly
BBlack: (0, 0), White: (255, 255, 255)
CBlack: (0, 0, 0), White: (255, 255)
DBlack: (0, 0, 0), White: (255, 255, 255)
Attempts:
2 left
💡 Hint
Tuple struct fields are accessed by dot and index number starting at 0.

Practice

(1/5)
1. What is the correct way to create an instance of a struct Person with fields name and age in Rust?
easy
A. let p = new Person { name: "Alice", age: 30 };
B. let p = Person("Alice", 30);
C. let p = Person { name: String::from("Alice"), age: 30 };
D. let p = Person(name = "Alice", age: 30);

Solution

  1. Step 1: Understand struct instance syntax

    In Rust, you create a struct instance by naming the struct and assigning values to each field inside curly braces.
  2. Step 2: Match the correct syntax

    let p = Person { name: String::from("Alice"), age: 30 }; uses Person { name: String::from("Alice"), age: 30 }, which is the correct way. Other options use incorrect syntax like tuple style or assignment inside parentheses.
  3. Final Answer:

    let p = Person { name: String::from("Alice"), age: 30 }; -> Option C
  4. Quick Check:

    Struct instance = StructName { field: value } [OK]
Hint: Use StructName { field: value } to create instances [OK]
Common Mistakes:
  • Using parentheses instead of curly braces
  • Trying to assign fields with = inside parentheses
  • Forgetting to convert string literals to String type
2. Which of the following is a syntax error when creating a struct instance Car with fields make and year?
easy
A. let c = Car { make: String::from("Toyota"), year: 2020 };
B. let c = Car { make: "Toyota", year: 2020 };
C. let c = Car { make: String::from("Toyota"), year: "2020" };
D. let c = Car { make: String::from("Toyota"), year: 2020 }

Solution

  1. Step 1: Check for syntax errors

    let c = Car { make: String::from("Toyota"), year: 2020 } is missing the semicolon after the let statement, which causes a syntax error in Rust.
  2. Step 2: Review other options

    Options A, B, and C have semicolons and valid struct syntax, though B and C may cause type errors if field types do not match.
  3. Final Answer:

    let c = Car { make: String::from("Toyota"), year: 2020 } -> Option D
  4. Quick Check:

    Semicolon required after let statements [OK]
Hint: Match field types exactly when creating struct instances [OK]
Common Mistakes:
  • Assigning string literals where String is expected without conversion
  • Using wrong data types for fields
  • Omitting semicolons (sometimes allowed but risky)
3. Given the struct and instance creation below, what will be printed?
struct Point {
    x: i32,
    y: i32,
}

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

Solution

  1. Step 1: Understand struct fields and instance values

    The struct Point has fields x and y. The instance p assigns x = 5 and y = 10.
  2. Step 2: Analyze the print statement

    The println! macro prints the values of p.x and p.y in order, so output is (5, 10).
  3. Final Answer:

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

    Print fields in order = (5, 10) [OK]
Hint: Print fields in order they appear in code [OK]
Common Mistakes:
  • Mixing up field order in print
  • Expecting field names printed instead of values
  • Assuming compilation error without reason
4. Identify the error in the following code that tries to create a struct instance:
struct Book {
    title: String,
    pages: u32,
}

fn main() {
    let b = Book { title: "Rust Book", pages: 300 };
}
medium
A. Missing semicolon after struct definition
B. String literal assigned directly to String field without conversion
C. Field name 'pages' is misspelled
D. Struct instance missing field values

Solution

  1. Step 1: Check field types and assigned values

    The field title is of type String, but the code assigns a string literal "Rust Book" directly, which is a "str" type, causing a type mismatch.
  2. Step 2: Confirm other parts are correct

    The field pages is correctly assigned an integer. The struct definition and instance have correct syntax otherwise.
  3. Final Answer:

    String literal assigned directly to String field without conversion -> Option B
  4. Quick Check:

    Convert "str" to String with String::from() [OK]
Hint: Convert string literals to String with String::from() [OK]
Common Mistakes:
  • Assigning "str" directly to String fields
  • Misspelling field names
  • Omitting required fields in instance
5. You have a struct Employee with fields name: String, id: u32, and active: bool. How do you create a new instance with name as "John", id as 101, and active as true, using shorthand for the active field if you have a variable active set to true?
hard
A. let active = true; let e = Employee { name: String::from("John"), id: 101, active };
B. let active = true; let e = Employee { name: "John", id: 101, active: active };
C. let e = Employee { name: String::from("John"), id: 101, active: true };
D. let active = true; let e = Employee { name: String::from("John"), id: 101, active = active };

Solution

  1. Step 1: Understand field shorthand syntax

    If a variable name matches a struct field name, you can use shorthand by just writing the variable name without field: value.
  2. Step 2: Identify correct usage

    let active = true; let e = Employee { name: String::from("John"), id: 101, active }; uses shorthand correctly: active variable is used directly as a field. let active = true; let e = Employee { name: "John", id: 101, active: active }; uses explicit active: active but has type mismatch on name. let e = Employee { name: String::from("John"), id: 101, active: true }; does not use the variable. let active = true; let e = Employee { name: String::from("John"), id: 101, active = active }; uses invalid syntax with = inside struct initialization.
  3. Final Answer:

    let active = true; let e = Employee { name: String::from("John"), id: 101, active }; -> Option A
  4. Quick Check:

    Use shorthand when variable name matches field name [OK]
Hint: Use field shorthand: just write variable name if it matches field [OK]
Common Mistakes:
  • Using = instead of : in struct initialization
  • Not converting string literals to String
  • Not using shorthand when possible
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