From c9997fb919ad1e79367ca1ce9d8bcc528bb73a49 Mon Sep 17 00:00:00 2001 From: Nick Treleaven Date: Thu, 12 Nov 2020 19:10:09 +0000 Subject: [PATCH] doc: split out `perform` from interface example (#6805) --- doc/docs.md | 34 ++++++++++++++++++++++------------ 1 file changed, 22 insertions(+), 12 deletions(-) diff --git a/doc/docs.md b/doc/docs.md index 8a10c8b9b6..26781c5164 100644 --- a/doc/docs.md +++ b/doc/docs.md @@ -1570,26 +1570,34 @@ interface Speaker { 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'} cat := Cat{} -println(perform(dog)) // "woof" -println(perform(cat)) // "meow" +mut arr := []Speaker{} +arr << dog +arr << cat +for item in arr { + item.speak() +} ``` A type implements an interface by implementing its methods. 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 ```v @@ -1629,6 +1637,8 @@ sum := World(Moon{}) println(sum) ``` +#### Dynamic casts + 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`: