| 1 | import math |
| 2 | |
| 3 | struct Any { |
| 4 | mut: |
| 5 | data voidptr |
| 6 | typ int |
| 7 | } |
| 8 | |
| 9 | fn 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 | |
| 21 | fn cast[T](obj Any) ?T { |
| 22 | if T.typ == obj.typ { |
| 23 | return *&T(obj.data) |
| 24 | } |
| 25 | return none |
| 26 | } |
| 27 | |
| 28 | fn 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 | |