doc: split out `perform` from interface example (#6805)
parent
21af7004ff
commit
c9997fb919
34
doc/docs.md
34
doc/docs.md
|
@ -1570,26 +1570,34 @@ interface Speaker {
|
||||||
speak() string
|
speak() string
|
||||||
}
|
}
|
||||||
|
|
||||||
fn perform(s Speaker) string {
|
|
||||||
if s is Dog { // use `is` to check the underlying type of an interface
|
|
||||||
println('perform(dog)')
|
|
||||||
println(s.breed) // `s` is automatically cast to `Dog` (smart cast)
|
|
||||||
} else if s is Cat {
|
|
||||||
println('perform(cat)')
|
|
||||||
}
|
|
||||||
return s.speak()
|
|
||||||
}
|
|
||||||
|
|
||||||
dog := Dog{'Leonberger'}
|
dog := Dog{'Leonberger'}
|
||||||
cat := Cat{}
|
cat := Cat{}
|
||||||
|
|
||||||
println(perform(dog)) // "woof"
|
mut arr := []Speaker{}
|
||||||
println(perform(cat)) // "meow"
|
arr << dog
|
||||||
|
arr << cat
|
||||||
|
for item in arr {
|
||||||
|
item.speak()
|
||||||
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
A type implements an interface by implementing its methods.
|
A type implements an interface by implementing its methods.
|
||||||
There is no explicit declaration of intent, no "implements" keyword.
|
There is no explicit declaration of intent, no "implements" keyword.
|
||||||
|
|
||||||
|
We can test the underlying type of an interface using dynamic cast operators:
|
||||||
|
```v oksyntax
|
||||||
|
fn announce(s Speaker) {
|
||||||
|
if s is Dog {
|
||||||
|
println('a $s.breed') // `s` is automatically cast to `Dog` (smart cast)
|
||||||
|
} else if s is Cat {
|
||||||
|
println('a cat')
|
||||||
|
} else {
|
||||||
|
println('something else')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
For more information, see [Dynamic casts](#dynamic-casts).
|
||||||
|
|
||||||
### Enums
|
### Enums
|
||||||
|
|
||||||
```v
|
```v
|
||||||
|
@ -1629,6 +1637,8 @@ sum := World(Moon{})
|
||||||
println(sum)
|
println(sum)
|
||||||
```
|
```
|
||||||
|
|
||||||
|
#### Dynamic casts
|
||||||
|
|
||||||
To check whether a sum type instance holds a certain type, use `sum is Type`.
|
To check whether a sum type instance holds a certain type, use `sum is Type`.
|
||||||
To cast a sum type to one of its variants you can use `sum as Type`:
|
To cast a sum type to one of its variants you can use `sum as Type`:
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue