1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

docs: improve the interface examples (#13422)

This commit is contained in:
kahsa 2022-02-10 19:28:40 +09:00 committed by GitHub
parent 9ed18efa53
commit b205e2fc67
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -2647,20 +2647,20 @@ particularly useful for initializing a C library.
## Type Declarations ## Type Declarations
### Interfaces ### Interfaces
```v ```v
// interface-example.1
struct Dog { struct Dog {
breed string breed string
} }
struct Cat {
breed string
}
fn (d Dog) speak() string { fn (d Dog) speak() string {
return 'woof' return 'woof'
} }
struct Cat {
breed string
}
fn (c Cat) speak() string { fn (c Cat) speak() string {
return 'meow' return 'meow'
} }
@ -2671,6 +2671,7 @@ interface Speaker {
speak() string speak() string
} }
fn main() {
dog := Dog{'Leonberger'} dog := Dog{'Leonberger'}
cat := Cat{'Siamese'} cat := Cat{'Siamese'}
@ -2680,6 +2681,7 @@ arr << cat
for item in arr { for item in arr {
println('a $item.breed says: $item.speak()') println('a $item.breed says: $item.speak()')
} }
}
``` ```
#### Implement an interface #### Implement an interface
@ -2691,6 +2693,7 @@ An interface can have a `mut:` section. Implementing types will need
to have a `mut` receiver, for methods declared in the `mut:` section to have a `mut` receiver, for methods declared in the `mut:` section
of an interface. of an interface.
```v ```v
// interface-example.2
module main module main
pub interface Foo { pub interface Foo {
@ -2734,20 +2737,29 @@ fn fn1(s Foo) {
We can test the underlying type of an interface using dynamic cast operators: We can test the underlying type of an interface using dynamic cast operators:
```v oksyntax ```v oksyntax
// interface-exmaple.3 (continued from interface-exampe.1)
interface Something {} interface Something {}
fn announce(s Something) { fn announce(s Something) {
if s is Dog { if s is Dog {
println('a $s.breed dog') // `s` is automatically cast to `Dog` (smart cast) println('a $s.breed dog') // `s` is automatically cast to `Dog` (smart cast)
} else if s is Cat { } else if s is Cat {
println('a $s.breed cat') println('a cat speaks $s.speak()')
} else { } else {
println('something else') println('something else')
} }
} }
fn main() {
dog := Dog{'Leonberger'}
cat := Cat{'Siamese'}
announce(dog)
announce(cat)
}
``` ```
```v ```v
// interface-example.4
interface IFoo { interface IFoo {
foo() foo()
} }