Type Declarations
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 and like TypeScript, V's interfaces can define fields, not just 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. There is no explicit declaration of intent, no “implements” keyword.
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
pub interface Foo {
write(string) string
}
// => the method signature of a type, implementing interface Foo should be:
// `pub fn (s Type) write(a string) string`
pub interface Bar {
mut:
write(string) string
}
// => the method signature of a type, implementing interface Bar should be:
// `pub fn (mut s Type) write(a string) string`
struct MyStruct {}
// MyStruct implements the interface Foo, but *not* interface Bar
pub 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'))
// }
Casting an interface
We can test the underlying type of an interface using dynamic cast operators:
// oksyntax
// interface-exmaple.3 (continued from interface-exampe.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() // Error.
b := a as IBar
dump(b)
b.bar()
}
}
}
For more information, see Dynamic casts.
Interface method definitions
Also unlike Go, an interface can have it’s 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)
.
N.B. 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 []byte) ?int
}
pub interface Writer {
mut:
write(buf []byte) ?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
}
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:
// oksyntax
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:
// oksyntax
my_filter := uppercase
You can pass the assigned function as an argument:
// oksyntax
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:
// oksyntax
println(filter('Hello world', uppercase))
And this works with anonymous functions as well:
// oksyntax
println(filter('Hello world', fn (s string) string {
return s.to_upper()
}))
You can see the complete example here.
Enums
enum Color {
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') }
}
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 cannot re-use reserved keywords. However, reserved keywords may be escaped with an @.
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
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
// oksyntax
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:
// ignore
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.
// ignore
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 {}
}
}
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.
Option/Result types and error handling
Option types are declared with ?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 an option type
return user
}
}
return error('User $id not found')
}
fn main() {
repo := Repo{
users: [User{1, 'Andrew'}, User{2, 'Bob'}, User{10, 'Charles'}]
}
user := repo.find_user_by_id(10) or { // Option types must be handled by `or` blocks
return
}
println(user.id) // "10"
println(user.name) // "Charles"
}
V combines Option
and Result
into one type, so you don’t need to decide which one to use.
The amount of work required to “upgrade” a function to an optional function is minimal;
you have to add a ?
to the return type and return an error when something goes wrong.
If you don’t need to return an error message, you can simply return none
(this is a more efficient equivalent of return error("")
).
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. err
is empty if none
was returned.
// oksyntax
user := repo.find_user_by_id(7) or {
println(err) // "User 7 not found"
return
}
Handling optionals
There are four ways of handling an optional. The first method is to propagate the error:
import net.http
fn f(url string) ?string {
resp := http.get(url)?
return resp.text
}
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 optional, the enclosing function must return
an optional 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:
// ignore
resp := http.get(url) or { return err }
return resp.text
The second method is to break from execution early:
// oksyntax
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 that break
and continue
can only be used inside a for
loop.
V does not have a way to forcibly “unwrap” an optional (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') // Could be `return none` as well
}
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.text) // resp is a http.Response, not an optional
} 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.