v2 / vlib / v / tests / comptime / comptime_smartcast_test.v
45 lines · 40 sloc · 804 bytes · 6488041a749df9762348d019c4223908c476f2e2
Raw
1type TestSum = int | string
2
3struct Abc {
4 s TestSum
5}
6
7fn gen[T, R](struc T) R {
8 $if T is $struct {
9 $for field in T.fields {
10 field_value := struc.$(field.name)
11 $if field_value is $sumtype {
12 $for v in field_value.variants {
13 if field_value is v { // smartcast
14 $if field_value is R {
15 dump(field_value)
16 return field_value
17 }
18 }
19 }
20 }
21 }
22 }
23 return R{}
24}
25
26fn test_int() {
27 a := Abc{TestSum(123)}
28 int_var := gen[Abc, int](a)
29 assert dump(int_var) == 123
30}
31
32fn test_str() {
33 b := Abc{TestSum('foo')}
34 str_var := gen[Abc, string](b)
35 assert dump(str_var) == 'foo'
36}
37
38fn test_both() {
39 a := Abc{TestSum(123)}
40 b := Abc{TestSum('foo')}
41 int_var := gen[Abc, int](a)
42 str_var := gen[Abc, string](b)
43 assert dump(str_var) == 'foo'
44 assert dump(int_var) == 123
45}
46