| 1 | interface Speaker { |
| 2 | say() string |
| 3 | } |
| 4 | |
| 5 | struct ChatRoom { |
| 6 | mut: |
| 7 | talkers map[string]Speaker |
| 8 | } |
| 9 | |
| 10 | fn new_room() &ChatRoom { |
| 11 | return &ChatRoom{ |
| 12 | talkers: map[string]Speaker{} |
| 13 | } |
| 14 | } |
| 15 | |
| 16 | fn (mut r ChatRoom) add(name string, s Speaker) { |
| 17 | r.talkers[name] = s |
| 18 | } |
| 19 | |
| 20 | fn test_using_a_map_of_speaker_interfaces() { |
| 21 | mut room := new_room() |
| 22 | room.add('my cat', Cat{ name: 'Tigga' }) |
| 23 | room.add('my dog', Dog{ name: 'Pirin' }) |
| 24 | room.add('stray dog', Dog{ name: 'Anoni' }) |
| 25 | room.add('me', Human{ name: 'Bilbo' }) |
| 26 | room.add('she', Human{ name: 'Maria' }) |
| 27 | mut text := '' |
| 28 | for name, subject in room.talkers { |
| 29 | line := '${name:12s}: ${subject.say()}' |
| 30 | println(line) |
| 31 | text += line |
| 32 | } |
| 33 | assert text.contains(' meows ') |
| 34 | assert text.contains(' barks ') |
| 35 | assert text.contains(' says ') |
| 36 | } |
| 37 | |
| 38 | struct Cat { |
| 39 | name string |
| 40 | } |
| 41 | |
| 42 | fn (c &Cat) say() string { |
| 43 | return '${c.name} meows "MEOW!"' |
| 44 | } |
| 45 | |
| 46 | struct Dog { |
| 47 | name string |
| 48 | } |
| 49 | |
| 50 | fn (d &Dog) say() string { |
| 51 | return '${d.name} barks "Bau Bau!"' |
| 52 | } |
| 53 | |
| 54 | struct Human { |
| 55 | name string |
| 56 | } |
| 57 | |
| 58 | fn (h &Human) say() string { |
| 59 | return '${h.name} says "Hello"' |
| 60 | } |
| 61 | |