v / cmd / v2 / test_sumtype3.v
44 lines · 38 sloc · 573 bytes · 388caee862d59ec9a34395423127ad9e9e5122aa
Raw
1struct Cat {
2 name string
3}
4
5struct Dog {
6 name string
7 age int
8}
9
10struct Bird {
11 name string
12 can_fly bool
13}
14
15type Animal = Bird | Cat | Dog
16
17fn make_conditional(which int) Animal {
18 result := if which == 0 {
19 Animal(Cat{
20 name: 'whiskers'
21 })
22 } else {
23 Animal(Bird{
24 name: 'tweety'
25 can_fly: true
26 })
27 }
28 return result
29}
30
31fn get_name(a Animal) string {
32 match a {
33 Cat { return a.name }
34 Dog { return a.name }
35 Bird { return a.name }
36 }
37}
38
39fn main() {
40 a := make_conditional(0)
41 b := make_conditional(1)
42 println(get_name(a))
43 println(get_name(b))
44}
45