More interface examples
This commit is contained in:
parent
a2513b3633
commit
60717ed15d
|
|
@ -2,21 +2,19 @@
|
||||||
|
|
||||||
struct Dog{
|
struct Dog{
|
||||||
breed string
|
breed string
|
||||||
speak() string
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn (d Dog) speak() string {
|
fn (d Dog) speak() string{
|
||||||
println('Woof')
|
return 'Woof'
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
struct Cat{
|
struct Cat{
|
||||||
breed string
|
breed string
|
||||||
speak() string
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn (c Cat) speak() string{
|
fn (c Cat) speak() string{
|
||||||
println('Meow')
|
return 'Meow'
|
||||||
}
|
}
|
||||||
|
|
||||||
interface Something{}
|
interface Something{}
|
||||||
|
|
@ -24,7 +22,7 @@ interface Something{}
|
||||||
|
|
||||||
fn announce(s Something){
|
fn announce(s Something){
|
||||||
if s is Dog {
|
if s is Dog {
|
||||||
println('a ${s.breed] dog')
|
println('a ${s.breed} dog')
|
||||||
}else if s is Cat{
|
}else if s is Cat{
|
||||||
println('a cat speaks ${s.speak()}')
|
println('a cat speaks ${s.speak()}')
|
||||||
}else {
|
}else {
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,36 @@
|
||||||
|
interface IFoo{
|
||||||
|
foo()
|
||||||
|
}
|
||||||
|
|
||||||
|
interface IBar{
|
||||||
|
bar()
|
||||||
|
}
|
||||||
|
|
||||||
|
struct SFoo{}
|
||||||
|
|
||||||
|
fn (sf SFoo) foo() {}
|
||||||
|
|
||||||
|
|
||||||
|
struct SFooBar {}
|
||||||
|
|
||||||
|
fn (sfb SFooBar) foo() {}
|
||||||
|
|
||||||
|
|
||||||
|
fn (sfb SFooBar) bar() {
|
||||||
|
dump('This implements IBar')
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main(){
|
||||||
|
|
||||||
|
mut arr := []IFoo{}
|
||||||
|
arr << SFoo{}
|
||||||
|
arr << SFooBar{}
|
||||||
|
|
||||||
|
for a in arr{
|
||||||
|
dump(a)
|
||||||
|
|
||||||
|
if a is IBar{
|
||||||
|
a.bar()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Loading…
Reference in New Issue