mirror of
https://github.com/vlang/v.git
synced 2023-08-10 21:13:21 +03:00
docs: smart casts
This commit is contained in:
parent
d547f74cb0
commit
55e75d57ae
14
doc/docs.md
14
doc/docs.md
@ -1435,6 +1435,7 @@ interface Speaker {
|
|||||||
fn perform(s Speaker) string {
|
fn perform(s Speaker) string {
|
||||||
if s is Dog { // use `is` to check the underlying type of an interface
|
if s is Dog { // use `is` to check the underlying type of an interface
|
||||||
println('perform(dog)')
|
println('perform(dog)')
|
||||||
|
println(s.breed) // `s` is automatically cast to `Dog` (smart cast)
|
||||||
} else if s is Cat {
|
} else if s is Cat {
|
||||||
println('perform(cat)')
|
println('perform(cat)')
|
||||||
}
|
}
|
||||||
@ -1460,9 +1461,18 @@ enum Color {
|
|||||||
mut color := Color.red
|
mut color := Color.red
|
||||||
// V knows that `color` is a `Color`. No need to use `color = Color.green` here.
|
// V knows that `color` is a `Color`. No need to use `color = Color.green` here.
|
||||||
color = .green
|
color = .green
|
||||||
println(color) // "1" TODO: print "green"?
|
println(color) // "green"
|
||||||
|
|
||||||
|
match color {
|
||||||
|
.red { ... }
|
||||||
|
.green { ... }
|
||||||
|
.blue { ... }
|
||||||
|
}
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Enum match must be exhaustive or have an `else` branch. This ensures that if a new enum field is added, it's handled everywhere in the code.
|
||||||
|
|
||||||
### Sum types
|
### Sum types
|
||||||
|
|
||||||
A sum type instance can hold a value of several different types. Use the `type`
|
A sum type instance can hold a value of several different types. Use the `type`
|
||||||
@ -1532,7 +1542,7 @@ fn (v Venus) sweat()
|
|||||||
|
|
||||||
fn pass_time(w World) {
|
fn pass_time(w World) {
|
||||||
match w {
|
match w {
|
||||||
// using the shadowed match variable, in this case `w`
|
// using the shadowed match variable, in this case `w` (smart cast)
|
||||||
Moon { w.moon_walk() }
|
Moon { w.moon_walk() }
|
||||||
Mars { w.shiver() }
|
Mars { w.shiver() }
|
||||||
else {}
|
else {}
|
||||||
|
Loading…
Reference in New Issue
Block a user