From 1f20127502e05e5df28d26f8614cb7005dea5b1d Mon Sep 17 00:00:00 2001 From: kahsa Date: Fri, 28 Jan 2022 17:09:52 +0900 Subject: [PATCH] doc: add example for interface casting (#13304) --- doc/docs.md | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/doc/docs.md b/doc/docs.md index 4c9ef7fb4e..7e61550cf4 100644 --- a/doc/docs.md +++ b/doc/docs.md @@ -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