From 0081e779692acf23704925cc5fd93645ed33c8e1 Mon Sep 17 00:00:00 2001 From: William Gooch Date: Sat, 30 Jan 2021 21:39:46 -0500 Subject: [PATCH] doc: document interface methods (#8360) --- doc/docs.md | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/doc/docs.md b/doc/docs.md index 7b58e02785..0bd79ac678 100644 --- a/doc/docs.md +++ b/doc/docs.md @@ -1931,6 +1931,46 @@ fn announce(s Speaker) { ``` For more information, see [Dynamic casts](#dynamic-casts). +Also unlike Go, an interface may implement a method. +These methods are not implemented by structs which implement that interface. + +When a struct is wrapped in an interface that has implemented a method +with the same name as one implemented by this struct, only the method +implemented on the interface is called. + +```v +struct Cat {} + +interface Adoptable {} + +fn (c Cat) speak() string { + return 'meow!' +} + +fn (a Adoptable) speak() string { + return 'adopt me!' +} + +fn (a Adoptable) adopt() ?&Cat { + if a is Cat { + return a + } else { + return error('This cannot be adopted.') + } +} + +fn new_adoptable() Adoptable { + return Cat{} +} + +fn main() { + adoptable := new_adoptable() + println(adoptable.speak()) // adopt me! + cat := adoptable.adopt() or { return } + println(cat.speak()) // meow! +} +``` + ### Enums ```v