Creating struct instances in Rust - Performance & Efficiency
When we create instances of a struct in Rust, we want to know how the time it takes changes as we create more instances.
We ask: How does the work grow when making many struct objects?
Analyze the time complexity of the following code snippet.
struct Point {
x: i32,
y: i32,
}
fn create_points(n: usize) -> Vec {
let mut points = Vec::new();
for i in 0..n {
points.push(Point { x: i as i32, y: i as i32 });
}
points
}
This code creates a list of n points, each with x and y set to the current index.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Loop runs
ntimes creating and adding a struct instance. - How many times: Exactly once per point, so
ntimes.
Each new point takes about the same time to create and add, so total work grows evenly with n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 creations and insertions |
| 100 | About 100 creations and insertions |
| 1000 | About 1000 creations and insertions |
Pattern observation: The work grows in a straight line as n grows.
Time Complexity: O(n)
This means the time to create points grows directly with how many points you want.
[X] Wrong: "Creating many struct instances is instant and does not depend on how many we make."
[OK] Correct: Each instance takes some time to build and store, so more instances mean more total time.
Understanding how creating many objects affects time helps you reason about program speed and resource use in real projects.
"What if we added a nested loop inside the creation loop that does a fixed amount of work? How would the time complexity change?"
Practice
Person with fields name and age in Rust?Solution
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.Step 2: Match the correct syntax
let p = Person { name: String::from("Alice"), age: 30 }; usesPerson { name: String::from("Alice"), age: 30 }, which is the correct way. Other options use incorrect syntax like tuple style or assignment inside parentheses.Final Answer:
let p = Person { name: String::from("Alice"), age: 30 }; -> Option CQuick Check:
Struct instance = StructName { field: value } [OK]
- Using parentheses instead of curly braces
- Trying to assign fields with = inside parentheses
- Forgetting to convert string literals to String type
Car with fields make and year?Solution
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.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.Final Answer:
let c = Car { make: String::from("Toyota"), year: 2020 } -> Option DQuick Check:
Semicolon required after let statements [OK]
- Assigning string literals where String is expected without conversion
- Using wrong data types for fields
- Omitting semicolons (sometimes allowed but risky)
struct Point {
x: i32,
y: i32,
}
fn main() {
let p = Point { x: 5, y: 10 };
println!("({}, {})", p.x, p.y);
}Solution
Step 1: Understand struct fields and instance values
The structPointhas fieldsxandy. The instancepassignsx = 5andy = 10.Step 2: Analyze the print statement
Theprintln!macro prints the values ofp.xandp.yin order, so output is(5, 10).Final Answer:
(5, 10) -> Option AQuick Check:
Print fields in order = (5, 10) [OK]
- Mixing up field order in print
- Expecting field names printed instead of values
- Assuming compilation error without reason
struct Book {
title: String,
pages: u32,
}
fn main() {
let b = Book { title: "Rust Book", pages: 300 };
}Solution
Step 1: Check field types and assigned values
The fieldtitleis of typeString, but the code assigns a string literal"Rust Book"directly, which is a "str" type, causing a type mismatch.Step 2: Confirm other parts are correct
The fieldpagesis correctly assigned an integer. The struct definition and instance have correct syntax otherwise.Final Answer:
String literal assigned directly to String field without conversion -> Option BQuick Check:
Convert "str" to String with String::from() [OK]
- Assigning "str" directly to String fields
- Misspelling field names
- Omitting required fields in instance
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?Solution
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 withoutfield: value.Step 2: Identify correct usage
let active = true; let e = Employee { name: String::from("John"), id: 101, active }; uses shorthand correctly:activevariable is used directly as a field. let active = true; let e = Employee { name: "John", id: 101, active: active }; uses explicitactive: activebut has type mismatch onname. 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.Final Answer:
let active = true; let e = Employee { name: String::from("John"), id: 101, active }; -> Option AQuick Check:
Use shorthand when variable name matches field name [OK]
- Using = instead of : in struct initialization
- Not converting string literals to String
- Not using shorthand when possible
Ready to prove it?
Pass the test and this pattern moves unknown
