doc: fix Interfaces example (#6499)
parent
4cd5153b32
commit
763ddf78f3
13
doc/docs.md
13
doc/docs.md
|
@ -1440,8 +1440,12 @@ particularly useful for initializing a C library.
|
||||||
### Interfaces
|
### Interfaces
|
||||||
|
|
||||||
```v
|
```v
|
||||||
struct Dog {}
|
struct Dog {
|
||||||
struct Cat {}
|
breed string
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Cat {
|
||||||
|
}
|
||||||
|
|
||||||
fn (d Dog) speak() string {
|
fn (d Dog) speak() string {
|
||||||
return 'woof'
|
return 'woof'
|
||||||
|
@ -1458,15 +1462,16 @@ interface Speaker {
|
||||||
fn perform(s Speaker) string {
|
fn perform(s Speaker) string {
|
||||||
if s is Dog { // use `is` to check the underlying type of an interface
|
if s is Dog { // use `is` to check the underlying type of an interface
|
||||||
println('perform(dog)')
|
println('perform(dog)')
|
||||||
println(s.breed) // `s` is automatically cast to `Dog` (smart cast)
|
println(s.breed) // `s` is automatically cast to `Dog` (smart cast)
|
||||||
} else if s is Cat {
|
} else if s is Cat {
|
||||||
println('perform(cat)')
|
println('perform(cat)')
|
||||||
}
|
}
|
||||||
return s.speak()
|
return s.speak()
|
||||||
}
|
}
|
||||||
|
|
||||||
dog := Dog{}
|
dog := Dog{'Leonberger'}
|
||||||
cat := Cat{}
|
cat := Cat{}
|
||||||
|
|
||||||
println(perform(dog)) // "woof"
|
println(perform(dog)) // "woof"
|
||||||
println(perform(cat)) // "meow"
|
println(perform(cat)) // "meow"
|
||||||
```
|
```
|
||||||
|
|
Loading…
Reference in New Issue