v2 / vlib / v / tests / comptime / comptime_methods_generic_struct_test.v
80 lines · 67 sloc · 1.01 KB · 45b7a0e6e2c9d12405819fdde486750101e13ccb
Raw
1interface El {
2 tag() string
3 content() ![]u8
4}
5
6struct Aa {
7 a string
8}
9
10fn (a Aa) tag() string {
11 return 'a'
12}
13
14fn (a Aa) content() ![]u8 {
15 return a.a.bytes()
16}
17
18struct Bb {
19 b string
20}
21
22fn (b Bb) tag() string {
23 return 'b'
24}
25
26fn (b Bb) content() ![]u8 {
27 return b.b.bytes()
28}
29
30struct Choi[T] implements El {
31 src []T
32}
33
34fn (c Choi[T]) tag() string {
35 return 'seq'
36}
37
38fn (c Choi[T]) content() ![]u8 {
39 mut out := []u8{}
40 for el in c.src {
41 out << el.tag().bytes()
42 out << el.content()!
43 }
44 return out
45}
46
47fn is_gelement[T]() int {
48 mut val := 0
49 $for meth in T.methods {
50 $if meth.name == 'tag' {
51 val += 1
52 }
53 $if meth.name == 'content' {
54 val += 1
55 }
56 }
57 return val
58}
59
60fn is_element[T]() bool {
61 $if T is El {
62 return true
63 }
64 return false
65}
66
67struct Per {
68 a Aa
69 b Bb
70 c Choi[Aa]
71 d string
72}
73
74fn test_main() {
75 assert dump(is_element[Aa]()) == true
76 assert dump(is_element[Bb]()) == true
77 assert dump(is_gelement[Bb]()) == 2
78 assert dump(is_element[Choi[Aa]]()) == true
79 assert dump(is_gelement[Choi[Bb]]()) == 2
80}
81