Struct definition
- Rust course
- Beginner
- Lesson 65/115
- 4 min
Define a fielded struct with struct.
Defining a struct
A struct is a custom type that groups related data under named fields. Each field has a name and a type:
struct Oyuncu {
ad: String,
puan: u32,
aktif: bool,
}Type names are written in PascalCase, field names in snake_case. The definition is only a template; memory is allocated when an instance is created.
Changing fields
To change a field, the whole instance must be mut; Rust doesn't allow marking individual fields as mutable:
let mut o = Oyuncu {
ad: String::from("Ece"),
puan: 120,
aktif: true,
};
o.puan += 30;
println!("{} {}", o.ad, o.puan); // Ece 150Practice First struct
Define an Oyuncu struct with the fields ad: String and puan: u32. Create an instance with ad = "Ece" and puan = 120, and print both fields separated by a space.
Starter code
fn main() {
// buraya yaz
}Sample solution
struct Oyuncu {
ad: String,
puan: u32,
}
fn main() {
let o = Oyuncu {
ad: String::from("Ece"),
puan: 120,
};
println!("{} {}", o.ad, o.puan);
}Expected output
Ece 120
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 How is a struct field accessed?
- With brackets: o["puan"]
- With an arrow: o->puan
- With colons: o::puan
- With a dot: o.puan Correct answer
Explanation: Rust always accesses fields with a dot; it auto-dereferences through references too.
2 Field type
struct Oyuncu {
ad: String,
puan: ____,
}
struct Oyuncu {
ad: String,
puan: u32,
}
Explanation: The score is a non-negative integer; u32 is a suitable type.
3 Concept and example
| Term | Meaning |
|---|---|
struct Oyuncu |
Type definition |
ad: String |
Field |
o.puan |
Field access |
let mut o |
Mutable instance |