如何創(chuàng)建異構(gòu)的對象集合?我想在一個(gè)中使用特征對象Vec。在C ++中我可以使一個(gè)基類Thing從中導(dǎo)出Monster1和Monster2。然后我可以創(chuàng)建一個(gè)std::vector<Thing*>。Thing對象必須存儲(chǔ)一些數(shù)據(jù),例如x : int, y : int,派生類需要添加更多數(shù)據(jù)。目前我有類似的東西struct Level {
// some stuff here
pub things: Vec<Box<ThingTrait + 'static>>,}struct ThingRecord {
x: i32,
y: i32,}struct Monster1 {
thing_record: ThingRecord,
num_arrows: i32,}struct Monster2 {
thing_record: ThingRecord,
num_fireballs: i32,}我定義了一個(gè)ThingTrait與方法get_thing_record(),attack(),make_noise()等,并實(shí)現(xiàn)它們的Monster1和Monster2。
如何創(chuàng)建異構(gòu)的對象集合?
ibeautiful
2019-08-13 17:24:43