docs: smart casts

pull/6212/head
Alexander Medvednikov 2020-08-24 11:14:35 +02:00 committed by GitHub
parent d547f74cb0
commit 55e75d57ae
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 12 additions and 2 deletions

View File

@ -1435,6 +1435,7 @@ interface Speaker {
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)')
}
@ -1460,9 +1461,18 @@ enum Color {
mut color := Color.red
// V knows that `color` is a `Color`. No need to use `color = Color.green` here.
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
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) {
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() }
Mars { w.shiver() }
else {}