| 1 | // Example of sum types |
| 2 | // Models a landing craft leaving orbit and landing on a world |
| 3 | import rand |
| 4 | import time |
| 5 | |
| 6 | struct Moon { |
| 7 | } |
| 8 | |
| 9 | struct Mars { |
| 10 | } |
| 11 | |
| 12 | fn (m Mars) dust_storm() bool { |
| 13 | return rand.int() >= 0 |
| 14 | } |
| 15 | |
| 16 | struct Venus { |
| 17 | } |
| 18 | |
| 19 | type World = Mars | Moon | Venus |
| 20 | |
| 21 | struct Lander { |
| 22 | } |
| 23 | |
| 24 | fn (l Lander) deorbit() { |
| 25 | println('leaving orbit') |
| 26 | } |
| 27 | |
| 28 | fn (l Lander) open_parachutes(n int) { |
| 29 | println('opening ${n} parachutes') |
| 30 | } |
| 31 | |
| 32 | fn wait() { |
| 33 | println('waiting...') |
| 34 | time.sleep(1 * time.second) |
| 35 | } |
| 36 | |
| 37 | fn (l Lander) land(w World) { |
| 38 | if w is Mars { |
| 39 | for w.dust_storm() { |
| 40 | wait() |
| 41 | } |
| 42 | } |
| 43 | l.deorbit() |
| 44 | match w { |
| 45 | Moon {} // no atmosphere |
| 46 | Mars { |
| 47 | // light atmosphere |
| 48 | l.open_parachutes(3) |
| 49 | } |
| 50 | Venus { |
| 51 | // heavy atmosphere |
| 52 | l.open_parachutes(1) |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | println('landed') |
| 57 | } |
| 58 | |
| 59 | fn main() { |
| 60 | l := Lander{} |
| 61 | l.land(Venus{}) |
| 62 | l.land(Mars{}) |
| 63 | } |
| 64 | |