| 1 | interface Speaker { |
| 2 | say_hello() string |
| 3 | speak(msg string) |
| 4 | } |
| 5 | |
| 6 | struct Boss { |
| 7 | name string |
| 8 | } |
| 9 | |
| 10 | fn (b Boss) say_hello() string { |
| 11 | return 'Hello, My name is ${b.name} and I\'m the bawz' |
| 12 | } |
| 13 | |
| 14 | fn (b Boss) speak(msg string) { |
| 15 | println(msg) |
| 16 | } |
| 17 | |
| 18 | struct Cat { |
| 19 | name string |
| 20 | breed string |
| 21 | } |
| 22 | |
| 23 | fn (c Cat) say_hello() string { |
| 24 | return 'Meow meow ${c.name} the ${c.breed} meow' |
| 25 | } |
| 26 | |
| 27 | fn (c Cat) speak(msg string) { |
| 28 | println('Meow ${msg}') |
| 29 | } |
| 30 | |
| 31 | struct Baz { |
| 32 | mut: |
| 33 | sp Speaker |
| 34 | } |
| 35 | |
| 36 | fn test_interface_struct() { |
| 37 | bz1 := Baz{ |
| 38 | sp: Boss{ |
| 39 | name: 'Richard' |
| 40 | } |
| 41 | } |
| 42 | assert bz1.sp.say_hello() == "Hello, My name is Richard and I'm the bawz" |
| 43 | print('Test Boss inside Baz struct: ') |
| 44 | bz1.sp.speak('Hello world!') |
| 45 | bz2 := Baz{ |
| 46 | sp: Cat{ |
| 47 | name: 'Grungy' |
| 48 | breed: 'Persian Cat' |
| 49 | } |
| 50 | } |
| 51 | assert bz2.sp.say_hello() == 'Meow meow Grungy the Persian Cat meow' |
| 52 | print('Test Cat inside Baz struct: ') |
| 53 | bz2.sp.speak('Hello world!') |
| 54 | } |
| 55 | |
| 56 | fn test_interface_mut_struct() { |
| 57 | mut mbaz := Baz{ |
| 58 | sp: Boss{ |
| 59 | name: 'Derek' |
| 60 | } |
| 61 | } |
| 62 | assert mbaz.sp.say_hello() == "Hello, My name is Derek and I'm the bawz" |
| 63 | mbaz.sp = Cat{ |
| 64 | name: 'Dog' |
| 65 | breed: 'Not a dog' |
| 66 | } |
| 67 | assert mbaz.sp.say_hello() == 'Meow meow Dog the Not a dog meow' |
| 68 | } |
| 69 | |
| 70 | fn test_interface_struct_from_array() { |
| 71 | bazs := [ |
| 72 | Baz{ |
| 73 | sp: Cat{ |
| 74 | name: 'Kitty' |
| 75 | breed: 'Catty Koo' |
| 76 | } |
| 77 | }, |
| 78 | Baz{ |
| 79 | sp: Boss{ |
| 80 | name: 'Bob' |
| 81 | } |
| 82 | }, |
| 83 | ] |
| 84 | assert bazs[0].sp.say_hello() == 'Meow meow Kitty the Catty Koo meow' |
| 85 | assert bazs[1].sp.say_hello() == "Hello, My name is Bob and I'm the bawz" |
| 86 | } |
| 87 | |
| 88 | fn test_interface_struct_from_mut_array() { |
| 89 | mut bazs := [ |
| 90 | Baz{ |
| 91 | sp: Cat{ |
| 92 | name: 'Kitty' |
| 93 | breed: 'Catty Koo' |
| 94 | } |
| 95 | }, |
| 96 | Baz{ |
| 97 | sp: Boss{ |
| 98 | name: 'Bob' |
| 99 | } |
| 100 | }, |
| 101 | ] |
| 102 | |
| 103 | bazs[0].sp = Boss{ |
| 104 | name: 'Ross' |
| 105 | } |
| 106 | |
| 107 | bazs[1].sp = Cat{ |
| 108 | name: 'Doggy' |
| 109 | breed: 'Doggy Doo' |
| 110 | } |
| 111 | |
| 112 | assert bazs[0].sp.say_hello() == "Hello, My name is Ross and I'm the bawz" |
| 113 | assert bazs[1].sp.say_hello() == 'Meow meow Doggy the Doggy Doo meow' |
| 114 | } |
| 115 | |