Bird
Raised Fist0
Rustprogramming~10 mins

Defining structs in Rust - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Defining structs
Start
↓
Define struct with fields
↓
Create instance of struct
↓
Access fields of instance
↓
Use instance in code
↓
End
This flow shows how you define a struct, create an instance, access its fields, and use it in your Rust program.
Execution Sample
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);
}
Defines a struct Person with name and age, creates an instance, and prints the values.
Execution Table
StepActionEvaluationResult
1Define struct Person with fields name and agestruct Person { name: String, age: u8 }Struct type Person created
2Create instance p with name="Alice", age=30Person { name: String::from("Alice"), age: 30 }Instance p created with name="Alice", age=30
3Access p.namep.name"Alice"
4Access p.agep.age30
5Print "{} is {} years old", p.name, p.ageprintln!("{} is {} years old", "Alice", 30)Output: Alice is 30 years old
💡 Program ends after printing the person's name and age.
Variable Tracker
VariableStartAfter Step 2Final
pundefinedPerson { name: "Alice", age: 30 }Person { name: "Alice", age: 30 }
Key Moments - 3 Insights
Why do we need to specify the type of each field in the struct?
Rust requires each field to have a type so it knows what kind of data to store and how much memory to allocate. See Step 1 in execution_table where the struct is defined with field types.
What happens if we try to access a field that does not exist in the struct?
Rust will give a compile-time error because the field is not defined. In the execution_table, only p.name and p.age are accessed successfully (Steps 3 and 4).
Why do we use String::from("Alice") instead of just "Alice"?
The field name is of type String, which is a growable string type. "Alice" alone is a string slice (&str). String::from converts the slice to a String. This is shown in Step 2.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of p.age at Step 4?
Au8
B"Alice"
C30
Dundefined
💡 Hint
Check Step 4 in execution_table where p.age is accessed and its value is shown.
At which step is the instance p created?
AStep 2
BStep 1
CStep 3
DStep 5
💡 Hint
Look at Step 2 in execution_table where p is assigned a Person instance.
If we change the age field type from u8 to String, what will happen?
AThe age field will store numbers as strings.
BA type mismatch error will occur at Step 2.
CThe code will compile and run as before.
DThe struct definition will cause a syntax error.
💡 Hint
Changing age to String means the assignment age: 30 (an integer) cannot be assigned to a String field, causing a compile-time type error at Step 2.
Concept Snapshot
Defining structs in Rust:
struct Name { field1: Type1, field2: Type2 }
Create instance: let var = Name { field1: val1, field2: val2 };
Access fields: var.field1
Fields must have types.
Use String::from for String fields.
Full Transcript
This example shows how to define a struct named Person with two fields: name of type String and age of type u8. Then, we create an instance p of Person with name set to "Alice" and age set to 30. We access the fields p.name and p.age to print the message "Alice is 30 years old". Each step is traced: defining the struct, creating the instance, accessing fields, and printing output. Important points include specifying field types, using String::from to create a String, and how Rust enforces field access at compile time.

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