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:
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.
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:
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
Output:
three
two
one
Function Types
You can use type aliases for naming specific function signatures - for example:
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.
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.
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:
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.
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:
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.
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
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.
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:
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:
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.