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:

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.

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.

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

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

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:

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

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

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.

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

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:

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

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:

type Expr = IntLit(int) | Count(int) | Str(string) | Void fn describe(e Expr) string { return match e { Expr.IntLit(n) { 'literal ${n}' } Expr.Count(n) { 'count ${n}' } Expr.Str(s) { 'string ${s}' } Expr.Void { 'void' } } } fn main() { e := Expr.Count(3) println(describe(e)) // count 3 println(e) // Expr.Count(3) println(e is Expr.Count) // true println(e == Expr.IntLit(3)) // false println(describe(Expr.Void)) // void }

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:

type Opt[T] = Some(T) | Nothing fn main() { a := Opt[int].Some(3) b := Opt[int].Nothing println(a) // Opt[int].Some(3) println(b) // Opt[int].Nothing println(a is Opt[int].Some) // true match a { Opt[int].Some(n) { println(n) } // 3 Opt[int].Nothing {} } }

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

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

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.

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

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.

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

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.

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.

interface Named { name string } struct User { name string age int } fn longest[T Named](a T, b T) T { return if a.name.len >= b.name.len { a } else { b } } type Number = int | f64 fn half[T Number](x T) T { return x / 2 } fn main() { println(longest(User{ name: 'ana' }, User{ name: 'leonor' }).name) // leonor println(half(7)) // 3 println(half(1.5)) // 0.75 }

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:

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.