Creating an instance
- Rust course
- Beginner
- Lesson 66/115
- 4 min
Create a struct instance and access its fields.
Creating instances
When creating an instance, every field must be given a value; order doesn't matter. If the variable name equals the field name, the field init shorthand is used:
fn yeni_oyuncu(ad: String) -> Oyuncu {
Oyuncu {
ad, // ad: ad
puan: 0,
aktif: true,
}
}A missing field is a "missing field" compile error; Rust doesn't assign default values automatically.
Printing with Debug
By default structs can't be printed with {} or {:?}. Once #[derive(Debug)] is added, {:?} gives one-line output and {:#?} indented output:
#[derive(Debug)]
struct Oyuncu { ad: String, puan: u32, aktif: bool }
let o = yeni_oyuncu(String::from("Ali"));
println!("{:?}", o);
// Oyuncu { ad: "Ali", puan: 0, aktif: true }dbg!(&o) writes to stderr together with the file and line.
Practice Builder function
Define Oyuncu { ad: String, puan: u32, aktif: bool } with #[derive(Debug)]. Let fn yeni_oyuncu(ad: String) -> Oyuncu set puan: 0 and aktif: true using the field shorthand. Create one for "Ali" and print it with {:?}.
Starter code
fn main() {
// buraya yaz
}Sample solution
#[derive(Debug)]
struct Oyuncu {
ad: String,
puan: u32,
aktif: bool,
}
fn yeni_oyuncu(ad: String) -> Oyuncu {
Oyuncu {
ad,
puan: 0,
aktif: true,
}
}
fn main() {
let o = yeni_oyuncu(String::from("Ali"));
println!("{:?}", o);
}Expected output
Oyuncu { ad: "Ali", puan: 0, aktif: true }
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Does <code>Oyuncu { ad, puan: 0 }</code> (without aktif) compile?
- Yes, aktif stays undefined
- It only warns
- No: the field aktif is missing Correct answer
- Yes, aktif becomes false
Explanation: All fields must be initialized. If you want defaults, use #[derive(Default)] and ..Default::default().
2 Derive Debug
#[derive(____)]
struct Oyuncu {
ad: String,
}
#[derive(Debug)]
struct Oyuncu {
ad: String,
}
Explanation: derive(Debug) generates the {:?} format automatically.
3 Syntax and meaning
| Term | Meaning |
|---|---|
Oyuncu { ad, .. } |
Field with shorthand |
#[derive(Debug)] |
{:?} support |
{:#?} |
Indented output |
dbg!(&o) |
Writes to stderr |