v2 / vlib / v / tests / generics / generic_comptime_arg_test.v
53 lines · 45 sloc · 970 bytes · 6488041a749df9762348d019c4223908c476f2e2
Raw
1import toml
2
3struct Parent {
4 name string
5 child1 Child1
6 child2 Child2
7}
8
9struct Child1 {
10 name string
11}
12
13struct Child2 {
14 age int
15}
16
17fn decode[T](toml_str string) !T {
18 doc := toml.parse_text(toml_str)!
19
20 return decode_struct(doc.to_any(), &T{})
21}
22
23// `T` param serves here as a workaround to allow to infer types of nested struct fields.
24fn decode_struct[T](doc toml.Any, typ &T) T {
25 mut res := T{}
26 $for field in T.fields {
27 val := doc.value(field.name)
28 $if field.typ is string {
29 res.$(field.name) = val.string()
30 } $else $if field.typ is int {
31 res.$(field.name) = val.int()
32 } $else $if field.is_struct {
33 typ_ := typ.$(field.name)
34 res.$(field.name) = decode_struct(val, &typ_)
35 }
36 }
37 return res
38}
39
40fn test_main() {
41 toml_str := 'name = "John"
42 child1 = { name = "abc" }
43 child2 = { age = 5 }'
44
45 a := dump(decode[Parent](toml_str)!)
46 assert a.name == 'John'
47 assert a.child1 == Child1{
48 name: 'abc'
49 }
50 assert a.child2 == Child2{
51 age: 5
52 }
53}
54