We can test the underlying type of an interface using dynamic cast operators:
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 .
enum Color {
red green blue
}
mut color := Color.red
// V knows that `color` is a `Color`. No need to use `color = Color.green` here.
color = .green
println(color) // "green"
match color {
.red { println('the color was red') }
.green { println('the color was green') }
.blue { println('the color was 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.
A sum type instance can hold a value of several different types. Use the type
keyword to declare a sum type:
struct Moon {}
struct Mars {}
struct Venus {}
type World = Mars | Moon | Venus
sum := World(Moon{})
assert sum.type_name() == 'Moon'
println(sum)
The built-in method type_name
returns the name of the currently held type.
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
:
struct Moon {}
struct Mars {}
struct Venus {}
type World = Mars | Moon | Venus
fn (m Mars) dust_storm() bool {
return true
}
fn main() {
mut w := World(Moon{})
assert w is Moon
// use `as` to access the Mars instance
mars := w as Mars
if mars.dust_storm() {
println('bad weather!')
}
}
as
will panic if w
doesn’t hold a Mars
instance. A safer way is to use a smart cast.
Smart casting
w
has type Mars
inside the body of the if
statement. This is known as flow-sensitive typing. You can also specify a variable name:
if w is Mars as mars {
assert typeof(w).name == 'World'
if mars.dust_storm() {
println('bad weather!')
}
}
Matching sum types
You can also use match
to determine the variant:
struct Moon {}
struct Mars {}
struct Venus {}
type World = Mars | Moon | Venus
fn open_parachutes(n int) {
println(n)
}
fn land(w World) {
match w {
Moon {} // no atmosphere
Mars {
// light atmosphere
open_parachutes(3)
}
Venus {
// heavy atmosphere
open_parachutes(1)
}
}
}
match
must have a pattern for each variant or have an else
branch.
There are two ways to access the cast variant inside a match branch:
- the shadowed match variable
- using
as
to specify a variable name
struct Moon {}
struct Mars {}
struct Venus {}
type World = Moon | Mars | Venus
fn (m Moon) moon_walk() {}
fn (m Mars) shiver() {}
fn (v Venus) sweat() {}
fn pass_time(w World) {
match w {
// using the shadowed match variable, in this case `w` (smart cast)
Moon { w.moon_walk() }
Mars { w.shiver() }
else {}
}
// using `as` to specify a name for each value
Mars { var.shiver() }
Venus { var.sweat() }
else {
// w is of type World
assert w is Moon
}
}
}
Note: shadowing only works when the match expression is a variable. It will not work on struct fields, array indexes, or map keys.
Option types are declared with ?Type
:
struct User {
id int
name string
}
struct Repo {
users []User
}
fn (r Repo) find_user_by_id(id int) ?User {
for user in r.users {
if user.id == id {
// V automatically wraps this into an option type
return user
}
}
}
fn main() {
repo := Repo{
users: [User{1, 'Andrew'}, User{2, 'Bob'},
User{10, 'Charles'},
]
}
user := repo.find_user_by_id(10) or { // Option types must be handled by `or` blocks
return
}
println(user.id) // "10"
println(user.name) // "Charles"
}
V combines Option
and Result
into one type, so you don’t need to decide which one to use.
The amount of work required to “upgrade” a function to an optional function is minimal; you have to add a ?
to the return type and return an error when something goes wrong.
If you don’t need to return an error message, you can simply return none
(this is a more efficient equivalent of return error("")
).
err
is defined inside an or
block and is set to the string message passed to the error()
function. err
is empty if none
was returned.
There are four ways of handling an optional. The first method is to propagate the error:
import net.http
fn f(url string) ?string {
resp := http.get(url) ?
return resp.text
}
http.get
returns ?http.Response
. Because ?
follows the call, the error will be propagated to the caller of f
. When using ?
after a function call producing an optional, the enclosing function must return an optional as well. If error propagation is used in the main()
function it will panic
instead, since the error cannot be propagated any further.
The body of f
is essentially a condensed version of:
resp := http.get(url) or { return error(err) }
return resp.text
The second method is to break from execution early:
user := repo.find_user_by_id(7) or { return }
Here, you can either call panic()
or exit()
, which will stop the execution of the entire program, or use a control flow statement (return
, break
, continue
, etc) to break from the current block. Note that break
and continue
can only be used inside a for
loop.
V does not have a way to forcibly “unwrap” an optional (as other languages do, for instance Rust’s unwrap()
or Swift’s !
). To do this, use or { panic(err) }
instead.
The third method is to provide a default value at the end of the or
block. In case of an error, that value would be assigned instead, so it must have the same type as the content of the Option
being handled.
fn do_something(s string) ?string {
if s == 'foo' {
return 'foo'
}
return error('invalid string') // Could be `return none` as well
}
a := do_something('foo') or { 'default' } // a will be 'foo'
b := do_something('bar') or { 'default' } // b will be 'default'
println(b)
Above, http.get
returns a ?http.Response
. resp
is only in scope for the first if
branch. err
is only in scope for the else
branch.