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:
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:
// 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:
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:
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:
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:
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.SomeandNoneare ordinary enum variants, and aTnever turns into a?Ton its own: you writeSome(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. deferruns 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.
switchcompares values with==, andmatchpicks by variant or type. The catch-all arm of both isdefault.
Coming from Zig
| In Zig | In 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 fn | export fn |
const std = @import("std"); | import { println } from "@fmt": names, not a namespace |
std.debug.print("{}\n", .{x}); | println(x) |
comptime T: type | known T: type |
an anytype parameter | a parameter of type _ |
comptime square(12) | known square(12) |
error{NotFound} | error LookupError { NotFound "not found"; }: each member carries a message |
E!T, inferred !T | E!T, inferred !T |
try f() | try f() |
f() catch 0 | f() catch 0 |
f() catch |e| handle(e) | f() catch handle |
opt orelse 0 | opt 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 union | match |
+%, -%, *% | +%, -%, *% |
@truncate(x) | u8(x): a conversion keeps the low bits |
defer, at the end of the block | defer, at the end of the function |
std.ArrayList(i32) | Vec(i32) from @core, created with an allocator |
an std.mem.Allocator parameter | an 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 Rust | In 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) = x | if Some(v) = x |
match on an enum | match |
match on numbers or strings | switch |
_ => | 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 Dog | interface Speaker; nothing to declare for Dog |
&dyn Speak | an interface value: con s: Speaker = &dog |
fn max<T: PartialOrd>(a: T, b: T) -> T | fn 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 i32 | fn x(p: *mut Point) *mut i32 '(p) |
Drop | defer where the resource is acquired |
a move closure | every closure copies what it captures |
Box::new(closure) to return it | alloc.put(*closure) |
x as u8 | u8(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 Go | In Vyi |
|---|---|
x := 5 | con x = 5, or mut x = 5 to reassign it |
var n int | mut n = 0: no zero value |
| a capitalized name to export it | export before the declaration, pub before a field |
func (p Point) Area() int | fn (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" |
nil | none: ?T and None |
fmt.Println(x) | println(x) |
for i := 0; i < n; i++ | for i in 0..n |
for _, x := range xs | for x in xs |
switch with optional default | switch 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]int | HashMap(String, i32) |
| implicit interface satisfaction | the same |
defer f(x) | defer f(x), which reads x when the function exits |
panic("boom") | panic "boom" |
recover() in a deferred function | recover(reason) { ... } inside a defer |
go f(), channels | concurrency 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 Swift | In Vyi |
|---|---|
let x = 5 | con x = 5 |
var x = 5 | mut x = 5 |
Int?, nil | ?i32, None |
let n: Int? = 5 | con n: ?i32 = Some(5): no implicit wrapping |
if let v = x | if Some(v) = x |
guard let v = x else { return } | con v = x catch { return } |
x ?? 0 | x 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 conformance | interface; nothing to declare on the type |
extension Point { func area() -> Int } | fn (p: Point) area() i32, in any file |
func f() throws -> Int | fn f() !i32 |
do { try f() } catch { ... } | f() catch { ... } |
class and reference counting | none: 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.