1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/*
use xreflect::Reflect;
// just derive Reflect
#[derive(Reflect)]
pub struct Enemy {
pub health: u8,
}
#[derive(Reflect)]
pub enum GameState {
Playing,
Won { score: i32, remaining_health: u8 },
Lost(Enemy),
}
fn main() {
// With Reflect, you can:
// 1. access and modify fields dynamically
let mut enemy = Enemy { health: 0 };
let enemy_health = enemy.field::<u8>("health");
enemy.set_field::<u8>("health", 7);
// 2. construct items dynamically
let mut game_state = GameState::Playing;
game_state = GameState::construct("Won")
.with_field::<f32>("score", 0.0)
.with_field::<u8>("remaining_health", 20);
game_state = GameState::construct("Lost").with_tuple_field::<Enemy>(0, enemy);
// 3. iterate through an item's fields and their types
for (field_name, field_type) in Enemy::fields() {
// both field_name and field_type are &str
match field_type {
"i32" => {
// note that you still have to provide the generic with the actual type
enemy.field::<i32>(field_name) = 1;
}
// custom types have convenience associated functions
GameState::type_name() => {}
}
}
}
*/
use TypeId;
use Reflect;
// just derive Reflect