doc: add example for interface casting (#13304)

pull/13307/head
kahsa 2022-01-28 17:09:52 +09:00 committed by GitHub
parent 8491e83e3f
commit 1f20127502
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 42 additions and 0 deletions

View File

@ -2743,6 +2743,48 @@ fn announce(s Something) {
}
}
```
```v
interface IFoo {
foo()
}
interface IBar {
bar()
}
// implements only IFoo
struct SFoo {}
fn (sf SFoo) foo() {}
// implements both IFoo and IBar
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)
// In order to execute instances that implements IBar.
if a is IBar {
// a.bar() // Error.
b := a as IBar
dump(b)
b.bar()
}
}
}
```
For more information, see [Dynamic casts](#dynamic-casts).
#### Interface method definitions