Type Declarations

Interfaces

  1. // interface-example.1
  2. struct Dog {
  3. breed string
  4. }
  5. fn (d Dog) speak() string {
  6. return 'woof'
  7. }
  8. struct Cat {
  9. breed string
  10. }
  11. fn (c Cat) speak() string {
  12. return 'meow'
  13. }
  14. // unlike Go and like TypeScript, V's interfaces can define fields, not just methods.
  15. interface Speaker {
  16. breed string
  17. speak() string
  18. }
  19. fn main() {
  20. dog := Dog{'Leonberger'}
  21. cat := Cat{'Siamese'}
  22. mut arr := []Speaker{}
  23. arr << dog
  24. arr << cat
  25. for item in arr {
  26. println('a $item.breed says: $item.speak()')
  27. }
  28. }

Implement an interface

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

An interface can have a mut: section. Implementing types will need to have a mut receiver, for methods declared in the mut: section of an interface.

  1. // interface-example.2
  2. module main
  3. pub interface Foo {
  4. write(string) string
  5. }
  6. // => the method signature of a type, implementing interface Foo should be:
  7. // `pub fn (s Type) write(a string) string`
  8. pub interface Bar {
  9. mut:
  10. write(string) string
  11. }
  12. // => the method signature of a type, implementing interface Bar should be:
  13. // `pub fn (mut s Type) write(a string) string`
  14. struct MyStruct {}
  15. // MyStruct implements the interface Foo, but *not* interface Bar
  16. pub fn (s MyStruct) write(a string) string {
  17. return a
  18. }
  19. fn main() {
  20. s1 := MyStruct{}
  21. fn1(s1)
  22. // fn2(s1) -> compile error, since MyStruct does not implement Bar
  23. }
  24. fn fn1(s Foo) {
  25. println(s.write('Foo'))
  26. }
  27. // fn fn2(s Bar) { // does not match
  28. // println(s.write('Foo'))
  29. // }

Casting an interface

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

  1. // oksyntax
  2. // interface-exmaple.3 (continued from interface-exampe.1)
  3. interface Something {}
  4. fn announce(s Something) {
  5. if s is Dog {
  6. println('a $s.breed dog') // `s` is automatically cast to `Dog` (smart cast)
  7. } else if s is Cat {
  8. println('a cat speaks $s.speak()')
  9. } else {
  10. println('something else')
  11. }
  12. }
  13. fn main() {
  14. dog := Dog{'Leonberger'}
  15. cat := Cat{'Siamese'}
  16. announce(dog)
  17. announce(cat)
  18. }
  1. // interface-example.4
  2. interface IFoo {
  3. foo()
  4. }
  5. interface IBar {
  6. bar()
  7. }
  8. // implements only IFoo
  9. struct SFoo {}
  10. fn (sf SFoo) foo() {}
  11. // implements both IFoo and IBar
  12. struct SFooBar {}
  13. fn (sfb SFooBar) foo() {}
  14. fn (sfb SFooBar) bar() {
  15. dump('This implements IBar')
  16. }
  17. fn main() {
  18. mut arr := []IFoo{}
  19. arr << SFoo{}
  20. arr << SFooBar{}
  21. for a in arr {
  22. dump(a)
  23. // In order to execute instances that implements IBar.
  24. if a is IBar {
  25. // a.bar() // Error.
  26. b := a as IBar
  27. dump(b)
  28. b.bar()
  29. }
  30. }
  31. }

For more information, see Dynamic casts.

Interface method definitions

Also unlike Go, an interface can have it’s own methods, similar to how structs can have their methods. These ‘interface methods’ do not have to be implemented, by structs which implement that interface. They are just a convenient way to write i.some_function() instead of some_function(i), similar to how struct methods can be looked at, as a convenience for writing s.xyz() instead of xyz(s).

N.B. This feature is NOT a “default implementation” like in C#.

For example, if a struct cat is wrapped in an interface a, that has implemented a method with the same name speak, as a method implemented by the struct, and you do a.speak(), only the interface method is called:

  1. interface Adoptable {}
  2. fn (a Adoptable) speak() string {
  3. return 'adopt me!'
  4. }
  5. struct Cat {}
  6. fn (c Cat) speak() string {
  7. return 'meow!'
  8. }
  9. struct Dog {}
  10. fn main() {
  11. cat := Cat{}
  12. assert dump(cat.speak()) == 'meow!'
  13. //
  14. a := Adoptable(cat)
  15. assert dump(a.speak()) == 'adopt me!' // call Adoptable's `speak`
  16. if a is Cat {
  17. // Inside this `if` however, V knows that `a` is not just any
  18. // kind of Adoptable, but actually a Cat, so it will use the
  19. // Cat `speak`, NOT the Adoptable `speak`:
  20. dump(a.speak()) // meow!
  21. }
  22. //
  23. b := Adoptable(Dog{})
  24. assert dump(b.speak()) == 'adopt me!' // call Adoptable's `speak`
  25. // if b is Dog {
  26. // dump(b.speak()) // error: unknown method or field: Dog.speak
  27. // }
  28. }

Embedded interface

Interfaces support embedding, just like structs:

  1. pub interface Reader {
  2. mut:
  3. read(mut buf []byte) ?int
  4. }
  5. pub interface Writer {
  6. mut:
  7. write(buf []byte) ?int
  8. }
  9. // ReaderWriter embeds both Reader and Writer.
  10. // The effect is the same as copy/pasting all of the
  11. // Reader and all of the Writer methods/fields into
  12. // ReaderWriter.
  13. pub interface ReaderWriter {
  14. Reader
  15. Writer
  16. }

Function Types

You can use type aliases for naming specific function signatures - for example:

  1. type Filter = fn (string) string

This works like any other type - for example, a function can accept an argument of a function type:

  1. type Filter = fn (string) string
  2. fn filter(s string, f Filter) string {
  3. return f(s)
  4. }

V has duck-typing, so functions don’t need to declare compatibility with a function type - they just have to be compatible:

  1. fn uppercase(s string) string {
  2. return s.to_upper()
  3. }
  4. // now `uppercase` can be used everywhere where Filter is expected

Compatible functions can also be explicitly cast to a function type:

  1. // oksyntax
  2. my_filter := Filter(uppercase)

The cast here is purely informational - again, duck-typing means that the resulting type is the same without an explicit cast:

  1. // oksyntax
  2. my_filter := uppercase

You can pass the assigned function as an argument:

  1. // oksyntax
  2. println(filter('Hello world', my_filter)) // prints `HELLO WORLD`

And you could of course have passed it directly as well, without using a local variable:

  1. // oksyntax
  2. println(filter('Hello world', uppercase))

And this works with anonymous functions as well:

  1. // oksyntax
  2. println(filter('Hello world', fn (s string) string {
  3. return s.to_upper()
  4. }))

You can see the complete example here.

Enums

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

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.

Enum fields cannot re-use reserved keywords. However, reserved keywords may be escaped with an @.

  1. enum Color {
  2. @none
  3. red
  4. green
  5. blue
  6. }
  7. color := Color.@none
  8. println(color)

Integers may be assigned to enum fields.

  1. enum Grocery {
  2. apple
  3. orange = 5
  4. pear
  5. }
  6. g1 := int(Grocery.apple)
  7. g2 := int(Grocery.orange)
  8. g3 := int(Grocery.pear)
  9. println('Grocery IDs: $g1, $g2, $g3')

Output: Grocery IDs: 0, 5, 6.

Operations are not allowed on enum variables; they must be explicitly cast to int.

Enums can have methods, just like structs.

  1. enum Cycle {
  2. one
  3. two
  4. three
  5. }
  6. fn (c Cycle) next() Cycle {
  7. match c {
  8. .one {
  9. return .two
  10. }
  11. .two {
  12. return .three
  13. }
  14. .three {
  15. return .one
  16. }
  17. }
  18. }
  19. mut c := Cycle.one
  20. for _ in 0 .. 10 {
  21. println(c)
  22. c = c.next()
  23. }

Output:

  1. one
  2. two
  3. three
  4. one
  5. two
  6. three
  7. one
  8. two
  9. three
  10. one

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.

With sum types you could build recursive structures and write concise but powerful code on them.

  1. // V's binary tree
  2. struct Empty {}
  3. struct Node {
  4. value f64
  5. left Tree
  6. right Tree
  7. }
  8. type Tree = Empty | Node
  9. // sum up all node values
  10. fn sum(tree Tree) f64 {
  11. return match tree {
  12. Empty { 0 }
  13. Node { tree.value + sum(tree.left) + sum(tree.right) }
  14. }
  15. }
  16. fn main() {
  17. left := Node{0.2, Empty{}, Empty{}}
  18. right := Node{0.3, Empty{}, Node{0.4, Empty{}, Empty{}}}
  19. tree := Node{0.5, left, right}
  20. println(sum(tree)) // 0.2 + 0.3 + 0.4 + 0.5 = 1.4
  21. }

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. // oksyntax
  2. if w is Mars {
  3. assert typeof(w).name == 'Mars'
  4. if w.dust_storm() {
  5. println('bad weather!')
  6. }
  7. }

w has type Mars inside the body of the if statement. This is known as flow-sensitive typing. If w is a mutable identifier, it would be unsafe if the compiler smart casts it without a warning. That’s why you have to declare a mut before the is expression:

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

Otherwise w would keep its original type.

This works for both, simple variables and complex expressions like user.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.

  1. // ignore
  2. struct Moon {}
  3. struct Mars {}
  4. struct Venus {}
  5. type World = Moon | Mars | Venus
  6. fn (m Moon) moon_walk() {}
  7. fn (m Mars) shiver() {}
  8. fn (v Venus) sweat() {}
  9. fn pass_time(w World) {
  10. match w {
  11. // using the shadowed match variable, in this case `w` (smart cast)
  12. Moon { w.moon_walk() }
  13. Mars { w.shiver() }
  14. else {}
  15. }
  16. }

Type aliases

To define a new type NewType as an alias for ExistingType, do type NewType = ExistingType.
This is a special case of a sum type declaration.

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'}, User{10, 'Charles'}]
  20. }
  21. user := repo.find_user_by_id(10) or { // Option types must be handled by `or` blocks
  22. return
  23. }
  24. println(user.id) // "10"
  25. println(user.name) // "Charles"
  26. }

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. // oksyntax
  2. user := repo.find_user_by_id(7) or {
  3. println(err) // "User 7 not found"
  4. return
  5. }

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. // ignore
  2. resp := http.get(url) or { return err }
  3. return resp.text

The second method is to break from execution early:

  1. // oksyntax
  2. 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.