v2 / vlib / v / tests / unions / union_implementing_interface_test.v
53 lines · 43 sloc · 818 bytes · 97e894747f27f4076891b66421460465b486c2b7
Raw
1interface Speaker {
2 speak() string
3}
4
5union MyUnion implements Speaker {
6 vint int
7 vu32 u32
8 vstring string
9}
10
11fn (u MyUnion) speak() string {
12 return 'hi, u.vint: ${unsafe { u.vint }}'
13}
14
15fn test_union_implementing_interface() {
16 s := Speaker(MyUnion{
17 vint: 123
18 })
19 assert s.speak() == 'hi, u.vint: 123'
20}
21
22interface Any {}
23
24struct Thing {}
25
26union Bad {
27 f f64
28 a Any
29}
30
31union BadBits {
32 f f64
33 bad Bad
34}
35
36fn bad_from_float(x f64) Bad {
37 bits := BadBits{
38 f: x
39 }
40 return unsafe { bits.bad }
41}
42
43fn test_union_str_with_invalid_interface_member_does_not_crash() {
44 x := [bad_from_float(2.0)]
45 assert x.str() == '[Bad{\n f: 2.0\n a: unknown interface value\n}]'
46}
47
48fn test_union_str_with_valid_interface_member_still_works() {
49 x := Bad{
50 a: Thing{}
51 }
52 assert x.str().contains('a: Any(Thing{})')
53}
54