How to unpack a struct in another struct in rust?
Can you do something like this?
struct Person {
hp: i32
}
struct EvolvedPerson开发者_运维技巧 {
hp: i32,
evolved_stat: i32,
}
let p1 = Person { hp: 10 }
let p2 = EvolvedPerson { ..p1, extra_stat: 20 }
Where the p2 now has the hp of p1.
Can you do something like this?
No. You can only unpack structs of the same type.
As a possible solution you can deconstruct p1
and then provide variables to p2
by shorter syntax:
struct Person {
hp: i32
}
struct EvolvedPerson {
hp: i32,
evolved_stat: i32,
}
let p1 = Person { hp: 10 };
let p2 = {
let Person { hp } = p1;
EvolvedPerson { hp, extra_stat: 20 }
};
The idiomatic way would be to include the Person
struct instead:
struct Person {
hp: i32,
}
struct EvolvedPerson {
person: Person,
evolved_stat: i32,
}
let p1 = Person { hp: 10 }
let p2 = EvolvedPerson { person: p1, extra_stat: 20 }
That way it is also trivial to implement AsRef<Person>
for EvolvedPerson
and thus you can use Person
methods with EvolvedPerson
too.
精彩评论