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.
Methods declared on a fixed-array alias keep that alias receiver, including methods whose names match builtin array methods.
Numeric aliases use ordinary conversions for initialization:
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:
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.
An unqualified enum name or alias in a struct field's default resolves in the struct's module. An importing module's same-named enum does not change that default, including in fixed arrays.
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:
The @ escape is also accepted in qualified and shorthand member references, including
comparisons, assignments, struct defaults, match branches, and constant integer expressions.
These references also work with the eval backend, with shorthand on either side of a comparison.
Enum initializers can refer to earlier keyword members, for example next = int(Kind.@struct) + 1.
Exact declarations take precedence: if both none and @none are declared, they retain distinct
values and match coverage.
Integers may be assigned to enum fields.
Output: Grocery IDs: 0, 5, 6.
Compile-time $if blocks can also be used inside enum bodies to include fields conditionally.
Operations are not allowed on enum variables; they must be explicitly cast to int.
Enums can have methods, just like structs.
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.from(value) returns a Result. It can be forwarded directly from a function returning
!Enum, preserving the enum value on success and the conversion error on failure.
Output:
three
two
one
Function Types
You can use type aliases for naming specific function signatures - for example:
Function signatures can include fixed-size arrays, pointers to fixed-size arrays, and other function types. Arrays of explicitly backed enums retain their element type in these signatures. This also applies to optional and result callback return types.
This works like any other type - for example, a function can accept an argument of a function type:
V has duck-typing, so functions don't need to declare compatibility with a function type - they just have to be compatible:
Compatible functions can also be explicitly cast to a function type:
The cast here is purely informational - again, duck-typing means that the resulting type is the same without an explicit cast:
You can pass the assigned function as an argument:
And you could of course have passed it directly as well, without using a local variable:
And this works with anonymous functions as well:
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.
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.
Fixed array fields are supported when converting a pointer to an interface with I(value)
or &I(value). Mutable fields continue to refer to the concrete object's fields.
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.
There is an optional implements keyword for explicit declaration
of intent, which applies to struct declarations.
Casting an interface
We can test the underlying type of an interface using dynamic cast operators.
[!NOTE] Dynamic cast converts variable
sinto a pointer inside theifstatements in this example:
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:
If you want to return the smart-casted pointer itself, use !&T as the return type instead.
Appending a smart-casted value to an array of its original interface type preserves the
complete interface value. Both animals << animal and animals << Animal(animal) retain
the underlying type and allow interface method calls on the appended element.
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.
Receiver methods are also available through embedded interfaces. A mutable receiver method updates the underlying concrete object's mutable fields, including when called through an interface pointer or multiple levels of interface embedding.
[!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:
Embedded interface
Interfaces support embedding, just like structs:
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:
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.
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:
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.
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:
Otherwise w would keep its original type.
This works for both simple variables and complex expressions like
user.nameandvalues[i]. The same rule applies to mutable method receivers, for examplefn (mut w World) fn_name() { for mut w is Mars { ... } }.
Smart casts also work on indexed expressions in match branches:
Matching sum types
You can also use match to determine the variant:
match must have a pattern for each variant or have an else branch.
Named variants
A sum type can also identify its variants by name instead of by type. Each named variant holds at most one payload, so two variants can carry the same payload type, and a variant can carry no payload at all:
A declaration is named as soon as one variant is written as Name(Type). Then every
variant is either Name(Type) or a bare Name without a payload, and its name must be
capitalized and unique in the sum type. The names belong to the sum type: Expr.Void does
not clash with a type called Void or with a Void variant of another sum type.
Declarations without any Name(Type) variant keep their usual meaning, where each variant
is a type.
Values are created with Expr.Count(3) and Expr.Void. A match branch like
Expr.Count(n) binds the payload to n. The binding is an immutable copy of the payload;
to change a value in a match mut branch, assign a new variant to the matched variable.
Payload bindings follow the same redeclaration and global shadowing rules as other local variables.
A branch can list several variants, like Expr.IntLit, Expr.Count {, when it binds no
payload. match must cover every variant or have an else branch, and is/!is checks
work with variants as well: e is Expr.Void. Two values are equal when they hold the same
variant and equal payloads.
Payloads can have any type, including structs, arrays, maps, options and other sum types,
and a payload can refer to its own sum type, like Node([]Tree) in
type Tree = Leaf(int) | Node([]Tree). A payload with several values is written as a
struct: Rect(Size). Generic sum types are supported too, but their values need explicit
type arguments:
$for v in Expr.variants iterates the named variants; typeof(v.typ).name gives their
names, like Expr.Count. Types in @[generated] modules can also use named variants
when their type names start with a lowercase letter or underscore.
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.
Trailing option-typed parameters can also be omitted in function calls.
When they are not passed, V supplies none:
An Option stores either a value or none. It has no error field and cannot carry an error as
its failure state. A Result stores either a value or an IError.
An IError may still be an ordinary Option payload, for example ?IError.
A function returning only ! or ? has no success payload. Its return type is a Result or
Option of void; callers still handle errors or absence with an or block or propagation.
With the C backend, Options store their payload inline. Wrapping a value or returning none
does not allocate; the payload itself can require allocation, as with arrays or interface values.
Results also store their payload inline, sharing storage between the value and error.
The success flag determines which is valid. An IError references its concrete error object;
msg() and code() dispatch to that object. Creating an error object may allocate.
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.
A Result's or block and failed if guard bind err to its IError.
Use err.msg() for its message and err.code() for its code.
An Option's or block or failed if guard does not bind err.
Any existing outer variable named err keeps its ordinary meaning in those blocks.
Use or { return none } to propagate absence, or construct an explicit error when converting
absence to a Result failure.
Use err is ... to compare errors:
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.
Handling options/results
There are four ways of handling an option/result. The first method is to propagate the error:
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:
The second method is to break from execution early:
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]
breakandcontinuecan only be used inside aforloop.
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.
The fourth method is to use if unwrapping:
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.
Generics
Cross-module privacy violations that do not depend on type parameters are diagnosed even in the program's unused generic functions and methods. Accesses that depend on type parameters are checked in concrete instances.
Generic method calls retain the declaring modules of their type arguments when selecting the concrete method, including methods returning Result or Option values.
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.
Type arguments retain the module where they are declared when used in a generic struct from another module, including arguments inside arrays, pointers, and maps.
Methods called on a generic factory result retain their dependencies in the compiled program.
Returning a generic struct as a generic interface retains its concrete methods, including when an interface type argument is itself a generic interface.
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. An explicitly specialized generic method can also be stored as a function value when the method is promoted from an embedded struct; the value binds that embedded receiver.
Editor hover and definition queries resolve generic type parameters within their declaration. A later declaration using a module type with the same name resolves to that module type.
Generic calls keep the identity of caller types even when an imported module declares a type with the same short name. Inside a generic declaration, its type parameters take precedence over same-named concrete types. A concrete single-letter struct can still be passed as a generic type argument.
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.
Nested generic calls preserve reference return types when passed directly to another generic call, including references stored as map values.
Another example:
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.
Generic type inference also works with field initialization shorthand in nested calls.
For struct Box[T] { value T } and fn wrap[U](box Box[U]) Box[U],
wrap(value: 42) infers U as int. The struct and function may use different
parameter names or arrange those parameters in a different order.
Constraints
A type parameter can name, after it, what its type arguments must be: an interface,
which a type argument implements; a sum type, or an alias of one, whose variants are
the types it takes; or a struct, which takes that struct and the structs that embed it.
A call is checked against the constraint where it is written, and in the body a value
of the type parameter has what the constraint provides: the members of the interface
or of the struct, or what every variant of the sum type has, operators included.
Nested generic sums retain the variants of each concrete instance. For example,
Part[int] | Part[string] accepts variants from both instances of Part[T].
Recursive sum constraints that keep growing their type arguments are rejected instead of
silently omitting nested variants. Finite recursive instances and aliases remain valid.
Modules referenced only by a generic constraint still count as used imports.
Struct constraints accept finite embedding paths without a depth limit.
longest(1, 2) is reported at the call: int does not implement Named. And a body
that used a.age would be reported too, as Named declares no age. In a branch of
$if T is f64 {, T is f64, and in its $else the rest of the set.
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:
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:
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 examplefn (e Expect[[]int]) ...) keeps precedence over a structured pattern. - A repeated placeholder must bind consistently:
Expect[map[K]K]onExpect[map[string]int]is rejected becauseKcannot be bothstringandint. - Raw
voidptris not allowed to bind into these patterns; cast through an explicit V type instead.