Summary - Structs
- Rust course
- Beginner
- Lesson 70/115
- 5 min
Combine fields and instantiation to build a point struct.
Structs summary
There are three struct forms: named fields (struct Oyuncu { ad: String }), tuple structs (struct Renk(u8, u8, u8);) and unit-like (struct Sessiz;). When creating an instance all fields are given; the field shorthand and the ..kaynak update syntax shorten the code. To change it, the whole instance must be mut. #[derive(Debug)] enables {:?} output.
Structs and functions
A function that processes a struct usually takes the parameter as a reference:
#[derive(Debug)]
struct Kutu { en: u32, boy: u32 }
fn alan(k: &Kutu) -> u32 {
k.en * k.boy
}Although this function works only with Kutu, it stands on its own. In the next group we'll move it into an impl block and make it a method: k.alan().
Practice Box area
Define Kutu { en: u32, boy: u32 } with #[derive(Debug)] and write fn alan(k: &Kutu) -> u32. Produce the output Kutu { en: 3, boy: 4 } alan=12 for Kutu { en: 3, boy: 4 }.
Starter code
fn main() {
// buraya yaz
}Sample solution
#[derive(Debug)]
struct Kutu {
en: u32,
boy: u32,
}
fn alan(k: &Kutu) -> u32 {
k.en * k.boy
}
fn main() {
let k = Kutu { en: 3, boy: 4 };
println!("{:?} alan={}", k, alan(&k));
}Expected output
Kutu { en: 3, boy: 4 } alan=12
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 If a function only reads a struct, what should the parameter be?
- k: &mut Kutu
- mut k: Kutu
- k: &Kutu Correct answer
- k: Kutu
Explanation: Taking a reference leaves ownership with the caller; the box can still be used after the function.
2 Create an instance
let k = Kutu ____;
let k = Kutu { en: 3, boy: 4 };
Explanation: A named-field struct instance is created with braces and field names.
3 Group summary
| Term | Meaning |
|---|---|
struct A { x: i32 } |
Named fields |
struct B(i32); |
Tuple struct |
struct C; |
Unit-like |
B { ..a } |
Update syntax |