Field update
- Rust course
- Beginner
- Lesson 69/115
- 4 min
Move fields from one struct to another with the .. syntax.
Struct update syntax
To copy most fields of an existing instance and change only some, ..kaynak is used; it's always written last:
let a = Oyuncu { ad: String::from("Ece"), puan: 10, aktif: true };
let b = Oyuncu { ad: String::from("Can"), ..a };
println!("{} {}", b.ad, b.puan); // Can 10Here puan and aktif are Copy types, so they are copied; a is still fully usable.
Partial moves
Only some fields of a struct can be moved; this is called a partial move. Access to the moved field and to the whole instance is forbidden; the remaining fields can be used:
let a = Oyuncu { ad: String::from("Ece"), puan: 10, aktif: true };
let b = Oyuncu { puan: 99, ..a };
println!("{}", a.puan); // fine: Copy
// println!("{}", a.ad); // error E0382
// let c = a; // error: a was partially movedTo avoid the move, you can write ..a.clone() (the struct must derive Clone).
Practice Derive a new player
Define Oyuncu { ad: String, puan: u32, aktif: bool }. Let a be Ece, 10, true. Create b with ad: "Can" and ..a. Print b.ad, b.puan, b.aktif and a.ad separated by spaces.
Starter code
fn main() {
// buraya yaz
}Sample solution
struct Oyuncu {
ad: String,
puan: u32,
aktif: bool,
}
fn main() {
let a = Oyuncu {
ad: String::from("Ece"),
puan: 10,
aktif: true,
};
let b = Oyuncu {
ad: String::from("Can"),
..a
};
println!("{} {} {} {}", b.ad, b.puan, b.aktif, a.ad);
}Expected output
Can 10 true Ece
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 After <code>let b = Oyuncu { puan: 99, ..a };</code>, can <code>a.ad</code> be used?
- Yes, it was copied
- Yes, it was borrowed
- b can't be created
- No: ad (a String) was moved into b Correct answer
Explanation: ..a moves the fields not given. Since String isn't Copy, a.ad is no longer valid (a.puan and a.aktif can still be used).
2 Copy the rest
let b = Oyuncu {
ad: String::from("Can"),
____
};
let b = Oyuncu {
ad: String::from("Can"),
..a
};
Explanation: ..a takes all fields not given from a and is written last.
3 Case and result
| Term | Meaning |
|---|---|
{ ad: yeni, ..a } then a.ad |
Usable |
{ puan: 1, ..a } then a.ad |
E0382 |
{ puan: 1, ..a } then a.puan |
Usable (Copy) |
..a.clone() |
No move |