vq / vlib / v / tests / interfaces / interfaces_map_test.v
60 lines · 50 sloc · 1.02 KB · 6488041a749df9762348d019c4223908c476f2e2
Raw
1interface Speaker {
2 say() string
3}
4
5struct ChatRoom {
6mut:
7 talkers map[string]Speaker
8}
9
10fn new_room() &ChatRoom {
11 return &ChatRoom{
12 talkers: map[string]Speaker{}
13 }
14}
15
16fn (mut r ChatRoom) add(name string, s Speaker) {
17 r.talkers[name] = s
18}
19
20fn 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
38struct Cat {
39 name string
40}
41
42fn (c &Cat) say() string {
43 return '${c.name} meows "MEOW!"'
44}
45
46struct Dog {
47 name string
48}
49
50fn (d &Dog) say() string {
51 return '${d.name} barks "Bau Bau!"'
52}
53
54struct Human {
55 name string
56}
57
58fn (h &Human) say() string {
59 return '${h.name} says "Hello"'
60}
61