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.
Enums
enum Color as u8 {
red
green
blue
}
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') }
}
The enum type can be any integer type, but can be omitted, if it is int
: enum Color {
.
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
.
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
// 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.
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)
}
// 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)
.
[!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
}
Sum types
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
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 are for types which may represent none
. Result types may
represent 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)
}
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
}
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
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]
Currently generic function definitions must declare their type parameters, but in
future V will infer generic type parameters from single-letter type names in
runtime parameter types. This is why find_by_id
can omit [T]
, because the
receiver argument r
uses a generic type T
.
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