v / cmd / v2 / test_sumtype2.v
50 lines · 42 sloc · 610 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_cat() Animal {
18 return Animal(Cat{
19 name: 'whiskers'
20 })
21}
22
23fn make_bird() Animal {
24 return Animal(Bird{
25 name: 'tweety'
26 can_fly: true
27 })
28}
29
30fn indirect() Animal {
31 a := make_cat()
32 return a
33}
34
35fn get_name(a Animal) string {
36 match a {
37 Cat { return a.name }
38 Dog { return a.name }
39 Bird { return a.name }
40 }
41}
42
43fn main() {
44 a := make_cat()
45 b := make_bird()
46 c := indirect()
47 println(get_name(a))
48 println(get_name(b))
49 println(get_name(c))
50}
51