v2 / vlib / v / tests / comptime / comptime_match_assign_test.v
91 lines · 76 sloc · 1.42 KB · 8e35f4d9848f7ad35d857a187dddbfd2eca5e19d
Raw
1import strconv
2
3fn test_comptime_match_assign() {
4 os := 'windows'
5 x := $match os {
6 'linux' { 'linux' }
7 'windows' { 'windows' }
8 $else { 'unknown' }
9 }
10
11 assert x == 'windows'
12
13 i := 123
14 y := $match i {
15 1 { '1' }
16 2 { '2' }
17 123 { '123' }
18 $else { 'unknown' }
19 }
20
21 assert y == '123'
22
23 j := true
24 z := $match j {
25 true { 'T' }
26 false { 'F' }
27 }
28
29 assert z == 'T'
30}
31
32fn test_comptime_match_assign_reverse() {
33 os1 := 'windows'
34 os2 := 'linux'
35 os3 := 'macos'
36 x := $match 'windows' {
37 os1 { 'w' }
38 os2 { 'l' }
39 os3 { 'm' }
40 $else { 'unknown' }
41 }
42
43 assert x == 'w'
44
45 b1 := true
46 b2 := false
47 b3 := true
48 y := $match false {
49 b1 { 'b1' }
50 b2 { 'b2' }
51 b3 { 'b3' }
52 $else { 'unknown' }
53 }
54
55 assert y == 'b2'
56
57 i1 := 123
58 i2 := 245
59 i3 := 1023
60 z := $match 1024 {
61 i1 { '123' }
62 i2 { '245' }
63 i3 { '1023' }
64 $else { 'unknown' }
65 }
66
67 assert z == 'unknown'
68}
69
70fn decode_number[T](str string) !T {
71 val := $match T.unaliased_typ {
72 i8 { strconv.atoi8(str)! }
73 i16 { strconv.atoi16(str)! }
74 i32 { strconv.atoi32(str)! }
75 i64 { strconv.atoi64(str)! }
76 u8 { strconv.atou8(str)! }
77 u16 { strconv.atou16(str)! }
78 u32 { strconv.atou32(str)! }
79 u64 { strconv.atou64(str)! }
80 int { strconv.atoi(str)! }
81 $float { T(strconv.atof_quick(str)) }
82 $else { return error('`decode_number` can not decode ${T.name} type') }
83 }
84
85 return val
86}
87
88fn test_comptime_match_assign_generic() {
89 x := decode_number[f32]('1.0')!
90 assert x == 1.0
91}
92