v2 / vlib / v / tests / generics / generics_T_typ_test.v
54 lines · 50 sloc · 916 bytes · 6488041a749df9762348d019c4223908c476f2e2
Raw
1import math
2
3struct Any {
4mut:
5 data voidptr
6 typ int
7}
8
9fn make_any[T](obj T) Any {
10 tsize := int(sizeof(T))
11 mut a := Any{
12 typ: T.typ
13 data: unsafe { malloc(tsize) }
14 }
15 unsafe {
16 vmemcpy(a.data, &obj, tsize)
17 }
18 return a
19}
20
21fn cast[T](obj Any) ?T {
22 if T.typ == obj.typ {
23 return *&T(obj.data)
24 }
25 return none
26}
27
28fn test_any_values() {
29 arr := [make_any(true), make_any(false), make_any(7), make_any('cat'),
30 make_any([3.1415926535])]
31 for elm in arr {
32 if b := cast[bool](elm) {
33 println(!b)
34 } else if i := cast[int](elm) {
35 println(i + 1)
36 } else if s := cast[string](elm) {
37 println(s + '!')
38 } else if f := cast[[]f64](elm) {
39 println(f[0])
40 }
41 }
42 if b := cast[bool](arr[0]) {
43 assert b == true
44 }
45 if b := cast[bool](arr[1]) {
46 assert b == false
47 }
48 if s := cast[string](arr[3]) {
49 assert s == 'cat'
50 }
51 if f := cast[[]f64](arr[4]) {
52 assert math.veryclose(f[0], 3.1415926535)
53 }
54}
55