Docs · Appendix

Coming from another language

This page is for programmers who know Zig, Rust, Go, or Swift. It starts with the ways Vyi's model differs from all four, then gives a table for each language: what you write there, and what you write in Vyi. The guides teach each topic in full.

What differs from all four

Methods come from scope and the pocket

A method is a function with a receiver, declared on its own, outside the type. A type's definition lists its fields and nothing else. Any file can declare a method for any type, including i32:

Vyi
import { println } from "@fmt"

fn (n: i32) doubled() i32 {
    return n * 2
}

fn main() !u8 {
    con width: i32 = 7
    println(width.doubled())   // prints 14
    return Ok(0)
}

A call value.method() looks for method first in scope where the call is written: the enclosing blocks, the file, and the file's imports. Then it looks in the type's pocket: the methods exported beside the type, which travel with it through imports and re-exports. A file that imports Rect gets the methods rect.vyi exported with it, without importing them by name:

Vyi
// file: rect.vyi
export struct Rect { pub width: i32, pub height: i32 }

export fn (r: Rect) area() i32 {
    return r.width * r.height
}

// file: main.vyi
import { println } from "@fmt"
import { Rect } from "./rect"

fn main() !u8 {
    con r = Rect{ width: 2, height: 3 }
    println(r.area())   // prints 6
    return Ok(0)
}

Nothing is global. A method you declare is seen by the code in its scope and, if you export it beside the type, by the files further along the import path. Converting a value to an interface picks its methods the same way, at the place you convert. Guide 14 builds the pocket up step by step, and guide 12 covers interfaces.

Values are copied, never moved

Assigning a value, passing it, and returning it all copy it. The original stays usable, and changing the copy leaves it alone:

Vyi
import { println } from "@fmt"

struct Point { x: i32, y: i32 }

fn main() !u8 {
    con start = Point{ x: 1, y: 2 }
    mut end = start
    end.x = 10
    println(start.x)   // prints 1
    println(end.x)     // prints 10
    return Ok(0)
}

To share a value instead, take a pointer to it: *mut T may write, *con T may only read. Several pointers to one value may exist at once. What the compiler checks is that a pointer never outlives what it points at (guide 09).

Lifetimes name parameters

A function that returns a pointer it was given can say what the result is tied to. The annotation after the return type names a parameter, not an abstract lifetime:

Vyi
import { println } from "@fmt"

struct Point { x: i32, y: i32 }

fn xOf(p: *mut Point) *mut i32 '(p) {
    return &p.x
}

fn main() !u8 {
    mut pt = Point{ x: 1, y: 2 }
    *xOf(&pt) = 10
    println(pt.x)   // prints 10
    return Ok(0)
}

'(p) reads "valid as long as what p points at". Without it, the compiler works the lifetime out from the body. With it, the compiler checks the body against the annotation, and every call against it too (guide 09). Memory from an allocator is yours to manage: once you free it, the compiler doesn't stop you from using a pointer into it.

Known values

Vyi runs ordinary code while it compiles. A value the compiler works out then is a known value. The known operator asks for one, and the same function still runs as usual elsewhere:

Vyi
import { println } from "@fmt"

fn square(n: i32) i32 {
    return n * n
}

fn main() !u8 {
    con area = known square(12)
    println(area)        // prints 144
    println(square(5))   // prints 25
    return Ok(0)
}

Types are known values too. A generic is a function that takes a `known T: type`, or one whose signature uses a type name you never declared, such as fn larger(a: T, b: T) T. Declarations can appear in any order, in any file (guide 11).

Memory comes from allocators

Vyi has no garbage collector and no hidden allocation. Memory that outlives a function comes from an allocator you pass in, and containers such as Vec and HashMap take one when you create them. A closure lives where it's written, so one that captures anything can't be returned:

Vyi · does not compile
fn adder(n: i32) fn(i32) i32 {
    return (x: i32) i32 => x + n   // error: frame-bound pointer
}

To keep it longer, put it into an allocator with alloc.put(*closure) (guide 04).

Smaller differences

  • No null. A value that may be missing has the type ?T. Some and None are ordinary enum variants, and a T never turns into a ?T on its own: you write Some(5).
  • Every binding starts with a value. There is no zero value and no undefined.
  • No implicit number conversions. i64(n) converts, and a conversion to a narrower integer keeps the low bits.
  • Integer overflow panics in a debug build and wraps in a release build. +%, -%, and *% always wrap.
  • defer runs when the function exits, not when the block ends, and it sees the values bindings have at that moment (guide 08).
  • Two ways to branch on a value. switch compares values with ==, and match picks by variant or type. The catch-all arm of both is default.

Coming from Zig

In ZigIn Vyi
const x = 5;con x = 5
var x: i32 = 0;mut x: i32 = 0
var x: i32 = undefined;none: every binding starts with a value
*T, *const T*mut T, *con T
?*T?*mut T
[]u8, []const u8[*mut]u8, [*con]u8
[3]i32{ 1, 2, 3 }[3]i32[1, 2, 3]
pub fnexport fn
const std = @import("std");import { println } from "@fmt": names, not a namespace
std.debug.print("{}\n", .{x});println(x)
comptime T: typeknown T: type
an anytype parametera parameter of type _
comptime square(12)known square(12)
error{NotFound}error LookupError { NotFound "not found"; }: each member carries a message
E!T, inferred !TE!T, inferred !T
try f()try f()
f() catch 0f() catch 0
f() catch |e| handle(e)f() catch handle
opt orelse 0opt catch 0
if (opt) |v| { ... }if Some(v) = opt { ... }
opt.?none: catch, if Some(v) = opt, or match
switch with else =>switch with default:
switch on a tagged unionmatch
+%, -%, *%+%, -%, *%
@truncate(x)u8(x): a conversion keeps the low bits
defer, at the end of the blockdefer, at the end of the function
std.ArrayList(i32)Vec(i32) from @core, created with an allocator
an std.mem.Allocator parameteran Allocator parameter, from @mem

A Vyi container keeps the allocator it was created with, so push takes no allocator. Errors are values as in Zig, and the open type error holds a member of any error declaration (guide 07).

Coming from Rust

In RustIn Vyi
let x = 5;con x = 5
let mut x = 5;mut x = 5
&T, &mut T*con T, *mut T
&str, &[T], &mut [T][*con]u8, [*con]T, [*mut]T
Option<i32>, Some(5), None?i32, Some(5), None
Result<i32, E>E!i32, or !i32 to infer E
f()?try f()
f().unwrap_or(0)f() catch 0
if let Some(v) = xif Some(v) = x
match on an enummatch
match on numbers or stringsswitch
_ =>default:
impl Point { fn area(&self) -> i32 }fn (p: *con Point) area() i32, outside any block
Point::new()Point.new(), declared fn (Point) new() Point
trait Speak and impl Speak for Doginterface Speaker; nothing to declare for Dog
&dyn Speakan interface value: con s: Speaker = &dog
fn max<T: PartialOrd>(a: T, b: T) -> Tfn max(a: T, b: T) T
Vec<i32>, HashMap<K, V>Vec(i32), HashMap(K, V) from @core, created with an allocator
fn x<'a>(p: &'a mut Point) -> &'a mut i32fn x(p: *mut Point) *mut i32 '(p)
Dropdefer where the resource is acquired
a move closureevery closure copies what it captures
Box::new(closure) to return italloc.put(*closure)
x as u8u8(x)
a.wrapping_add(b)a +% b
println!("{}", x)println(x)

There are no moves and no borrow rules: values copy, and a pointer only has to stay within the life of what it points at. There is no orphan rule either: any file can declare methods for any type, and interfaces need no impl, since a type satisfies one when the methods are found for it.

Coming from Go

In GoIn Vyi
x := 5con x = 5, or mut x = 5 to reassign it
var n intmut n = 0: no zero value
a capitalized name to export itexport before the declaration, pub before a field
func (p Point) Area() intfn (p: Point) area() i32
func (p *Point) Grow()fn (p: *mut Point) grow()
v, err := f(); if err != nil { return err }con v = try f()
v, err := f(); if err != nil { v = 0 }con v = f() catch 0
errors.New("disk is full")error DiskFull "disk is full"
nilnone: ?T and None
fmt.Println(x)println(x)
for i := 0; i < n; i++for i in 0..n
for _, x := range xsfor x in xs
switch with optional defaultswitch with default, unless the arms cover every value
switch v := x.(type)match typeof x, on a union type such as i32 | bool
[]int[*mut]i32 for a view, Vec(i32) to append to
map[string]intHashMap(String, i32)
implicit interface satisfactionthe same
defer f(x)defer f(x), which reads x when the function exits
panic("boom")panic "boom"
recover() in a deferred functionrecover(reason) { ... } inside a defer
go f(), channelsconcurrency is (planned) (guide 18)

Go evaluates a deferred call's arguments at the defer statement; Vyi evaluates the whole defer body when the function exits. Methods aren't tied to the type's package: any file can declare them for any type. And with no garbage collector, a closure that captures anything can't be returned without an allocator (above).

Coming from Swift

In SwiftIn Vyi
let x = 5con x = 5
var x = 5mut x = 5
Int?, nil?i32, None
let n: Int? = 5con n: ?i32 = Some(5): no implicit wrapping
if let v = xif Some(v) = x
guard let v = x else { return }con v = x catch { return }
x ?? 0x catch 0
x!x catch { panic "missing" }
enum Shape { case circle(Int) }enum Shape { Circle(i32) }
switch over cases, case .circle(let r):match with Circle(r):
switch over values, default:switch with default:
protocol and a conformanceinterface; nothing to declare on the type
extension Point { func area() -> Int }fn (p: Point) area() i32, in any file
func f() throws -> Intfn f() !i32
do { try f() } catch { ... }f() catch { ... }
class and reference countingnone: structs, pointers, and allocators
print(x)println(x)
"total: \(n)"$"total: ${n}"

Structs and enums are values in both languages. Vyi has no classes: sharing is an explicit pointer, and memory beyond a function comes from an allocator instead of reference counting. A Vyi try passes the error on to the caller; catch handles it where it happens.