Type Declarations

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.

Numeric aliases use ordinary conversions for initialization:

type Decimal = f64 amount := Decimal(0.0)

Enums

Methods on an ordinary enum keep their definitions even when another module declares a flag enum with the same type name.

An enum is a group of constant integer values, each having its own name, whose values start at 0 and increase by 1 for each name listed. For example:

enum Color as u8 { red // the default start value is 0 green // the value is automatically incremented to 1 blue // the final value is now 2 } 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') } } println(int(color)) // prints 1

The enum type can be any integer type, but can be omitted, if it is int: enum Color {. When a struct field expects an enum, its value can use the short .field form, including inside parentheses in a collapsed struct call argument.

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 can re-use reserved keywords:

enum Color { none red green blue } color := Color.none println(color)

Integers may be assigned to enum fields.

enum Grocery { apple orange = 5 pear } g1 := int(Grocery.apple) g2 := int(Grocery.orange) g3 := int(Grocery.pear) println('Grocery IDs: ${g1}, ${g2}, ${g3}')

Output: Grocery IDs: 0, 5, 6.

Compile-time $if blocks can also be used inside enum bodies to include fields conditionally.

enum Feature { base $if beta ? { beta_extension } }

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

Enums can have methods, just like structs.

enum Cycle { one two three } fn (c Cycle) next() Cycle { match c { .one { return .two } .two { return .three } .three { return .one } } } mut c := Cycle.one for _ in 0 .. 10 { println(c) c = c.next() }

Output:

one
two
three
one
two
three
one
two
three
one

Enums can be created from string or integer value and converted into string

enum Cycle { one two = 2 three } // Create enum from value println(Cycle.from(10) or { Cycle.three }) println(Cycle.from('two')!) // Convert an enum value to a string println(Cycle.one.str())

Output:

three
two
one

Function Types

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

type Filter = fn (string) string

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

type Filter = fn (string) string fn filter(s string, f Filter) string { return f(s) }

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

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

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

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:

my_filter := uppercase

You can pass the assigned function as an argument:

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:

println(filter('Hello world', uppercase))

And this works with anonymous functions as well:

println(filter('Hello world', fn (s string) string { return s.to_upper() }))

You can see the complete example here.

Interfaces

A mutable interface alias can use mut value as OtherInterface when its source is mutable. A narrowed interface value can be cast for an immediate scalar getter that only reads fields. Type tests joined by || do not narrow the value in the true branch; they do not require mut unless a nested condition itself narrows the value. A negative type guard whose body exits also narrows the value after the guard and requires mut.

Casting a pointer to an interface can be used directly as the receiver of a method returning multiple values. Interface data fields retain their individual types during the conversion.

// interface-example.1 struct Dog { breed string } fn (d Dog) speak() string { return 'woof' } struct Cat { breed string } fn (c Cat) speak() string { return 'meow' } // unlike Go, but like TypeScript, V's interfaces can define both fields and methods. interface Speaker { breed string speak() string } fn main() { dog := Dog{'Leonberger'} cat := Cat{'Siamese'} mut arr := []Speaker{} arr << dog arr << cat for item in arr { println('a ${item.breed} says: ${item.speak()}') } }

Implement an interface

A type implements an interface by implementing its methods and fields. Equivalent fixed array lengths in method signatures may use different constant expressions. Callback userdata parameters may use voidptr or a concrete pointer type. An interface field's default value may be a pointer to a type that implements the interface.

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.

// interface-example.2 module main interface Foo { write(string) string } // => the method signature of a type, implementing interface Foo should be: // `fn (s Type) write(a string) string` interface Bar { mut: write(string) string } // => the method signature of a type, implementing interface Bar should be: // `fn (mut s Type) write(a string) string` struct MyStruct {} // MyStruct implements the interface Foo, but *not* interface Bar fn (s MyStruct) write(a string) string { return a } fn main() { s1 := MyStruct{} fn1(s1) // fn2(s1) -> compile error, since MyStruct does not implement Bar } fn fn1(s Foo) { println(s.write('Foo')) } // fn fn2(s Bar) { // does not match // println(s.write('Foo')) // }

There is an optional implements keyword for explicit declaration of intent, which applies to struct declarations.

struct PathError implements IError { Error path string } fn (err PathError) msg() string { return 'Failed to open path: ${err.path}' } fn try_open(path string) ! { return PathError{ path: path } } fn main() { try_open('/tmp') or { panic(err) } }

Casting an interface

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

[!NOTE] Dynamic cast converts variable s into a pointer inside the if statements in this example:

// interface-example.3 (continued from interface-example.1) interface Something {} fn announce(s Something) { if s is Dog { println('a ${s.breed} dog') // `s` is automatically cast to `Dog` (smart cast) } else if s is Cat { println('a cat speaks ${s.speak()}') } else { println('something else') } } fn main() { dog := Dog{'Leonberger'} cat := Cat{'Siamese'} announce(dog) announce(cat) }

Smart casting an interface value to T also means the smart-casted variable has type &T inside that branch. This matters when returning the value from a generic function:

fn get_component[T](entity Entity) !T { for component in entity.components { if component is T { return *component } } return error('Entity does not have component') }

If you want to return the smart-casted pointer itself, use !&T as the return type instead.

// interface-example.4 interface IFoo { foo() } interface IBar { bar() } // implements only IFoo struct SFoo {} fn (sf SFoo) foo() {} // implements both IFoo and IBar struct SFooBar {} fn (sfb SFooBar) foo() {} fn (sfb SFooBar) bar() { dump('This implements IBar') } fn main() { mut arr := []IFoo{} arr << SFoo{} arr << SFooBar{} for a in arr { dump(a) // In order to execute instances that implements IBar. if a is IBar { a.bar() } } }

For more information, see Dynamic casts.

Interface method definitions

Also unlike Go, an interface can have its 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).

An immediate read-only interface method call on a smart-casted value can return a scalar, including char, rune, isize, usize, or an enum.

[!NOTE] 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:

interface Adoptable {} fn (a Adoptable) speak() string { return 'adopt me!' } struct Cat {} fn (c Cat) speak() string { return 'meow!' } struct Dog {} fn main() { cat := Cat{} assert dump(cat.speak()) == 'meow!' a := Adoptable(cat) assert dump(a.speak()) == 'adopt me!' // call Adoptable's `speak` if a is Cat { // Inside this `if` however, V knows that `a` is not just any // kind of Adoptable, but actually a Cat, so it will use the // Cat `speak`, NOT the Adoptable `speak`: dump(a.speak()) // meow! } b := Adoptable(Dog{}) assert dump(b.speak()) == 'adopt me!' // call Adoptable's `speak` // if b is Dog { // dump(b.speak()) // error: unknown method or field: Dog.speak // } }

Embedded interface

Interfaces support embedding, just like structs:

pub interface Reader { mut: read(mut buf []u8) ?int } pub interface Writer { mut: write(buf []u8) ?int } // ReaderWriter embeds both Reader and Writer. // The effect is the same as copy/pasting all of the // Reader and all of the Writer methods/fields into // ReaderWriter. pub interface ReaderWriter { Reader Writer }

An interface value smart cast to a struct refers to the concrete object stored in the interface. It can be dereferenced to copy the struct or returned through a struct reference. This applies to single-type match branches as well as if and assert smart casts. For a value pattern such as item is T, a function returning that struct by value can copy the smart-casted value directly, including through ?T and !T returns and if/match expressions. An explicit pointer pattern such as item is &T requires *item to copy the struct by value.

Sum types

Mapping an array variant inside a match branch infers the result element type from the mapper.

Assignments to common struct fields also work through sum type array elements, including compound assignments after filtering or smart casting other elements.

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.

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

// V's binary tree struct Empty {} struct Node { value f64 left Tree right Tree } type Tree = Empty | Node // sum up all node values fn sum(tree Tree) f64 { return match tree { Empty { 0 } Node { tree.value + sum(tree.left) + sum(tree.right) } } } fn main() { left := Node{0.2, Empty{}, Empty{}} right := Node{0.3, Empty{}, Node{0.4, Empty{}, Empty{}}} tree := Node{0.5, left, right} println(sum(tree)) // 0.2 + 0.3 + 0.4 + 0.5 = 1.4 }

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 w = Mars{} // 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

if w is Mars { assert typeof(w).name == 'Mars' if w.dust_storm() { println('bad weather!') } }

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:

if mut w is Mars { assert typeof(w).name == 'Mars' if w.dust_storm() { println('bad weather!') } }

Otherwise w would keep its original type.

This works for both simple variables and complex expressions like user.name and values[i]. The same rule applies to mutable method receivers, for example fn (mut w World) fn_name() { for mut w is Mars { ... } }.

Smart casts also work on indexed expressions in match branches:

type Entry = int | string values := [Entry('v')] match values[0] { string { assert values[0] == 'v' } else { assert false } }

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.

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 {} } }

Option/Result types and error handling

Option types can represent a value or none. Result types may represent a value, or an error returned from a function.

Option types are declared by prepending ? to the type name: ?Type. Result types use !: !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 a result or option type return user } } return error('User ${id} not found') } // A version of the function using an option fn (r Repo) find_user_by_id2(id int) ?User { for user in r.users { if user.id == id { return user } } return none } fn main() { repo := Repo{ users: [User{1, 'Andrew'}, User{2, 'Bob'}, User{10, 'Charles'}] } user := repo.find_user_by_id(10) or { // Option/Result types must be handled by `or` blocks println(err) return } println(user.id) // "10" println(user.name) // "Charles" user2 := repo.find_user_by_id2(10) or { return } // To create an Option var directly: my_optional_int := ?int(none) my_optional_string := ?string(none) my_optional_user := ?User(none) }

Trailing option-typed parameters can also be omitted in function calls. When they are not passed, V supplies none:

fn connect(url string, timeout ?int) { actual_timeout := timeout or { 1000 } println('${url} -> ${actual_timeout}') } fn main() { connect('https://vlang.io') connect('https://vlang.io', 5000) }

V used to combine Option and Result into one type, now they are separate.

The amount of work required to "upgrade" a function to an option/result function is minimal; you have to add a ? or ! to the return type and return none or an error (respectively) when something goes wrong.

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.

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

Use err is ... to compare errors:

import io x := read() or { if err is io.Eof { println('end of file') } return }

A local err declared in a nested block shadows the implicit or error variable, including in result values.

Options/results when returning multiple values

Only one Option or Result is allowed to be returned from a function. It is possible to return multiple values and still signal an error.

fn multi_return(v int) !(int, int) { if v < 0 { return error('must be positive') } return v, v * v }

Handling options/results

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

import net.http fn f(url string) !string { resp := http.get(url)! return resp.body }

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 option, the enclosing function must return an option 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 err } return resp.body

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] break and continue can only be used inside a for loop.

V does not have a way to forcibly "unwrap" an option (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') } a := do_something('foo') or { 'default' } // a will be 'foo' b := do_something('bar') or { 'default' } // b will be 'default' println(a) println(b)

The fourth method is to use if unwrapping:

import net.http if resp := http.get('https://google.com') { println(resp.body) // resp is a http.Response, not an option } else { println(err) }

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.

Custom error types

V gives you the ability to define custom error types through the IError interface. The interface requires two methods: msg() string and code() int. Every type that implements these methods can be used as an error.

When defining a custom error type it is recommended to embed the builtin Error default implementation. This provides an empty default implementation for both required methods, so you only have to implement what you really need, and may provide additional utility functions in the future.

struct PathError { Error path string } fn (err PathError) msg() string { return 'Failed to open path: ${err.path}' } fn try_open(path string) ! { // V automatically casts this to IError return PathError{ path: path } } fn main() { try_open('/tmp') or { panic(err) } }

Generics

Omitted fields of a generic struct use their declared defaults, including in nested structs. This also applies through concrete generic aliases and imported structs; defaults use the imports visible in the declaring file. Fixed array fields initialize each element with its specialized generic defaults.

Generic types brought into scope by a selective import retain their declaring module when passed to generic functions and methods in other modules.

struct Repo[T] { db DB } struct User { id int name string } struct Post { id int user_id int title string body string } fn new_repo[T](db DB) Repo[T] { return Repo[T]{db: db} } // This is a generic function. V will generate it for every type it's used with. fn (r Repo[T]) find_by_id(id int) ?T { table_name := T.name // in this example getting the name of the type gives us the table name return r.db.query_one[T]('select * from ${table_name} where id = ?', id) } db := new_db() users_repo := new_repo[User](db) // returns Repo[User] posts_repo := new_repo[Post](db) // returns Repo[Post] user := users_repo.find_by_id(1)? // find_by_id[User] post := posts_repo.find_by_id(1)? // find_by_id[Post]

A generic method retains its receiver type when called inside a function returning multiple values, including a Result tuple. The enclosing return type does not replace receiver arguments. This also applies when a value from a Result tuple is returned as an interface.

Generic calls keep the identity of caller types even when an imported module declares a type with the same short name.

Currently generic function definitions must declare their type parameters, but in future versions, V will infer generic type parameters from single-letter type names in runtime parameter types. This is why the find_by_id(1) calls above can omit [T], because the receiver argument r in the method declaration, uses a generic type T.

Receiver inference also works across module imports and aliases. Declared receiver types are resolved in the module that defines the method, so a caller type with the same name does not change the inferred type arguments. typeof(call()).name reports the concrete return type of an inferred generic method call. Inference also follows receivers obtained by unwrapping an option or propagating a result.

Another example:

fn compare[T](a T, b T) int { if a < b { return -1 } if a > b { return 1 } return 0 } // compare[int] println(compare(1, 0)) // Outputs: 1 println(compare(1, 1)) // 0 println(compare(1, 2)) // -1 // compare[string] println(compare('1', '0')) // Outputs: 1 println(compare('1', '1')) // 0 println(compare('1', '2')) // -1 // compare[f64] println(compare(1.1, 1.0)) // Outputs: 1 println(compare(1.1, 1.1)) // 0 println(compare(1.1, 1.2)) // -1

V can also infer a generic callback's return type from an unbound instance method passed as an argument, such as item.call(Item.value) when call[T] accepts a fn (mut Item) T callback.

Structured generic receiver patterns

Generic methods can constrain their receiver to a structured shape of the wrapped type, and the checker will bind the inner type parameters from the concrete receiver.

The most common case is requiring the wrapped type to be a dynamic array:

struct Expect[T] { value T } fn (e Expect[[]T]) first_or(value T) T { if e.value.len == 0 { return value } return e.value[0] } fn main() { a := Expect[[]int]{ value: [1, 2, 3] } println(a.first_or(0)) // 1, T is bound to int b := Expect[[]string]{ value: []string{} } println(b.first_or('none')) // none, T is bound to string }

Nested array patterns are matched recursively, so Expect[[][]int] binds T = []int, and Expect[[]map[string]int] binds T = map[string]int.

Maps work the same way and can bind two parameters at once:

struct Expect[T] { value T } fn (e Expect[map[K]V]) get_or(key K, value V) V { if key in e.value { return e.value[key] } return value } fn main() { m := Expect[map[string]int]{ value: { 'a': 1 } } println(m.get_or('a', 0)) // 1 (K = string, V = int) println(m.get_or('b', -1)) // -1 }

Expect[map[string]map[string]int] binds K = string and V = map[string]int.

Rules:

  • Expect[[]T] matches dynamic arrays; fixed-size arrays are not matched.
  • Expect[map[K]V] matches maps.
  • Nested patterns are matched recursively.
  • Plain generic receivers like Expect[T] continue to work, and an exact concrete receiver method (for example fn (e Expect[[]int]) ...) keeps precedence over a structured pattern.
  • A repeated placeholder must bind consistently: Expect[map[K]K] on Expect[map[string]int] is rejected because K cannot be both string and int.
  • Raw voidptr is not allowed to bind into these patterns; cast through an explicit V type instead.