Types 2

Interfaces

  1. struct Dog {
  2. breed string
  3. }
  4. struct Cat {}
  5. fn (d Dog) speak() string {
  6. return 'woof'
  7. }
  8. fn (c Cat) speak() string {
  9. return 'meow'
  10. }
  11. interface Speaker {
  12. speak() string
  13. }
  14. dog := Dog{'Leonberger'}
  15. cat := Cat{}
  16. mut arr := []Speaker{}
  17. arr << dog
  18. arr << cat
  19. for item in arr {
  20. item.speak()
  21. }

A type implements an interface by implementing its methods. There is no explicit declaration of intent, no “implements” keyword.

We can test the underlying type of an interface using dynamic cast operators:

  1. fn announce(s Speaker) {
  2. if s is Dog {
  3. println('a $s.breed') // `s` is automatically cast to `Dog` (smart cast)
  4. } else if s is Cat {
  5. println('a cat')
  6. } else {
  7. println('something else')
  8. }
  9. }

For more information, see Dynamic casts.

Enums

  1. enum Color {
  2. red green blue
  3. }
  4. mut color := Color.red
  5. // V knows that `color` is a `Color`. No need to use `color = Color.green` here.
  6. color = .green
  7. println(color) // "green"
  8. match color {
  9. .red { println('the color was red') }
  10. .green { println('the color was green') }
  11. .blue { println('the color was blue') }
  12. }

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 keyword to declare a sum type:

  1. struct Moon {}
  2. struct Mars {}
  3. struct Venus {}
  4. type World = Mars | Moon | Venus
  5. sum := World(Moon{})
  6. assert sum.type_name() == 'Moon'
  7. 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:

  1. struct Moon {}
  2. struct Mars {}
  3. struct Venus {}
  4. type World = Mars | Moon | Venus
  5. fn (m Mars) dust_storm() bool {
  6. return true
  7. }
  8. fn main() {
  9. mut w := World(Moon{})
  10. assert w is Moon
  11. w = Mars{}
  12. // use `as` to access the Mars instance
  13. mars := w as Mars
  14. if mars.dust_storm() {
  15. println('bad weather!')
  16. }
  17. }

as will panic if w doesn’t hold a Mars instance. A safer way is to use a smart cast.

Smart casting

  1. if w is Mars {
  2. assert typeof(w).name == 'Mars'
  3. if w.dust_storm() {
  4. println('bad weather!')
  5. }
  6. }

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:

  1. if w is Mars as mars {
  2. assert typeof(w).name == 'World'
  3. if mars.dust_storm() {
  4. println('bad weather!')
  5. }
  6. }

w keeps its original type. This form is necessary if w is a more complex expression than just a variable name.

Matching sum types

You can also use match to determine the variant:

  1. struct Moon {}
  2. struct Mars {}
  3. struct Venus {}
  4. type World = Mars | Moon | Venus
  5. fn open_parachutes(n int) {
  6. println(n)
  7. }
  8. fn land(w World) {
  9. match w {
  10. Moon {} // no atmosphere
  11. Mars {
  12. // light atmosphere
  13. open_parachutes(3)
  14. }
  15. Venus {
  16. // heavy atmosphere
  17. open_parachutes(1)
  18. }
  19. }
  20. }

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
  1. struct Moon {}
  2. struct Mars {}
  3. struct Venus {}
  4. type World = Moon | Mars | Venus
  5. fn (m Moon) moon_walk() {}
  6. fn (m Mars) shiver() {}
  7. fn (v Venus) sweat() {}
  8. fn pass_time(w World) {
  9. match w {
  10. // using the shadowed match variable, in this case `w` (smart cast)
  11. Moon { w.moon_walk() }
  12. Mars { w.shiver() }
  13. else {}
  14. }
  15. // using `as` to specify a name for each value
  16. match w as var {
  17. Mars { var.shiver() }
  18. Venus { var.sweat() }
  19. else {
  20. // w is of type World
  21. assert w is Moon
  22. }
  23. }
  24. }

Note: shadowing only works when the match expression is a variable. It will not work on struct fields, array indexes, or map keys.

Option/Result types and error handling

Option types are declared with ?Type:

  1. struct User {
  2. id int
  3. name string
  4. }
  5. struct Repo {
  6. users []User
  7. }
  8. fn (r Repo) find_user_by_id(id int) ?User {
  9. for user in r.users {
  10. if user.id == id {
  11. // V automatically wraps this into an option type
  12. return user
  13. }
  14. }
  15. return error('User $id not found')
  16. }
  17. fn main() {
  18. repo := Repo{
  19. users: [User{1, 'Andrew'}, User{2, 'Bob'},
  20. User{10, 'Charles'},
  21. ]
  22. }
  23. user := repo.find_user_by_id(10) or { // Option types must be handled by `or` blocks
  24. return
  25. }
  26. println(user.id) // "10"
  27. println(user.name) // "Charles"
  28. }

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("")).

This is the primary mechanism for error handling in V. They are still values, like in Go, but the advantage is that errors can’t be unhandled, and handling them is a lot less verbose. Unlike other languages, V does not handle exceptions with throw/try/catch blocks.

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.

  1. user := repo.find_user_by_id(7) or {
  2. println(err) // "User 7 not found"
  3. return
  4. }

Handling optionals

There are four ways of handling an optional. The first method is to propagate the error:

  1. import net.http
  2. fn f(url string) ?string {
  3. resp := http.get(url) ?
  4. return resp.text
  5. }

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:

  1. resp := http.get(url) or { return error(err) }
  2. return resp.text

The second method is to break from execution early:

  1. 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.

  1. fn do_something(s string) ?string {
  2. if s == 'foo' {
  3. return 'foo'
  4. }
  5. return error('invalid string') // Could be `return none` as well
  6. }
  7. a := do_something('foo') or { 'default' } // a will be 'foo'
  8. b := do_something('bar') or { 'default' } // b will be 'default'
  9. println(a)
  10. println(b)

The fourth method is to use if unwrapping:

  1. import net.http
  2. if resp := http.get('https://google.com') {
  3. println(resp.text) // resp is a http.Response, not an optional
  4. } else {
  5. println(err)
  6. }

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.