Guides · 02
Values and bindings
A Vyi program is built from values with names. This guide shows how to give a
value a name with con, mut, and type, which primitive types exist, how to
write literals, and how to convert a value from one type to another.
Three rules run through all of it:
- A binding can't change unless you declare it with
mut. - Every binding starts with a value.
- One number type never turns into another unless you write the conversion.
con and mut
con declares a binding that can't change. mut declares one that can. Vyi
works out the type from the value, or you can write the type after a colon:
import { println } from "@fmt"
fn main() !u8 {
con price = 250 // type worked out: i32
con tax: i32 = 20 // type written out
mut total = 0
total += price
total += tax
println(total) // prints 270
return Ok(0)
}Use con unless you need to reassign. Most values never change after they're
created, and con tells the next reader so. Assigning to a con binding is an
error:
fn main() !u8 {
con limit = 10
limit = 20 // error: cannot reassign immutable binding
return Ok(0)
}con covers the whole value, not only the name. You can't change a field of a
struct or an element of an array held in a con binding either. Declare it
with mut if you plan to modify it:
struct Point { x: i32, y: i32 }
fn main() !u8 {
con p = Point{ x: 1, y: 2 }
p.x = 10 // error: cannot write through immutable binding
return Ok(0)
}A mut binding can take new values, but its type stays the same for its whole
life.
Every binding starts with a value
Vyi has no "declare now, set later" and no automatic zero. A binding without
= value is an error:
mut count: i32 // error: a binding always takes a valueSo a name never exists without a value, and reading an uninitialized variable
is a bug you can't write. If you don't have the real value yet, start from an
explicit one, such as mut count = 0.
Bindings outside a function
A binding written outside any function is a file-level variable. It starts
from a value the compiler can work out before the program runs, because no code
runs before main. Calling a function is fine as long as the compiler can
evaluate it. A function that does something only a running program can do,
such as printing, is not:
import { println } from "@fmt"
fn askLimit() i32 {
println("limit?")
return 10
}
con limit = askLimit() // error: not a value the compiler can
fn main() !u8 { return Ok(0) }To use a value like that, compute it in main, or in a function main calls.
The rule is the same for a file-level mut.
Shadowing
Declaring a name inside a block, when the same name already exists outside it, creates a new binding that hides the outer one until the block ends:
import { println } from "@fmt"
fn main() !u8 {
con score = 5
if true {
con score = 100
println(score) // prints 100
}
println(score) // prints 5
return Ok(0)
}Shadowing doesn't change the outer value. The inner score is a separate
binding, and it disappears at the end of its block.
Within a single block, a name can be declared only once. Declaring it again is an error, not a shadow. (Functions are the exception: several functions can share a name as overloads, as guide 04 explains.)
fn main() !u8 {
con score = 5
con score = 100 // error: duplicate declaration of "score"
return Ok(0)
}To build a value up in steps, use mut, or give each step its own name.
type bindings
type gives a name to a type. The most common use is an alias, which is
interchangeable with the type it names:
import { println } from "@fmt"
type Meters = i32
fn twice(distance: Meters) Meters {
return distance * 2
}
fn main() !u8 {
con track: Meters = 400
con steps: i32 = 50
println(twice(track)) // prints 800
println(twice(steps)) // prints 100
return Ok(0)
}Meters is i32. Passing steps, an i32, where a Meters is expected needs
no conversion.
An alias can also have methods of its own. A value declared as Meters has
every method of i32, plus the methods written for Meters. A plain i32
doesn't get the Meters methods:
import { println } from "@fmt"
type Meters = i32
fn (m: Meters) toKilometers() i32 { return m / 1000 }
fn main() !u8 {
con trip: Meters = 5000
println(trip.toKilometers()) // prints 5
return Ok(0)
}A binding declared as a plain i32, such as con n: i32 = 5000, has no
toKilometers method, so n.toKilometers() would not compile. The methods reference
has the full rules.
Values as types
type accepts more than existing types. It accepts any known value: a
value the compiler works out while compiling. A plain value used as a type
means "the type whose only value is this one". Joined with |, several values
make a type that holds any one of them:
import { println } from "@fmt"
type Mode = "fast" | "slow"
fn delay(mode: Mode) i32 {
return switch mode { "fast": 1, "slow": 20 }
}
fn main() !u8 {
con mode: Mode = "slow" // a Mode is "fast" or "slow"
println(delay(mode)) // prints 20
return Ok(0)
}delay uses switch (guide 05) to pick a result by the
value of mode. It handles "fast" and "slow" and needs no other case,
because a Mode can't hold anything else. Giving a Mode any other value is
an error:
type Mode = "fast" | "slow"
fn main() !u8 {
con mode: Mode = "medium" // error: this value has type [*con]u8, but the binding is declared "fast" | "slow"
return Ok(0)
}Because a known value can come from a function call, type is also how Vyi
makes generic types. A generic type is a function that returns a type:
import { println } from "@fmt"
fn Box(known T: type) type {
return struct { value: T }
}
type IntBox = Box(i32)
fn main() !u8 {
con b = IntBox{ value: 7 }
println(b.value) // prints 7
return Ok(0)
}Guide 11, Known values and generics, covers this in depth.
Primitive types
| Type | What it holds |
|---|---|
i8 i16 i32 i64 | signed integers of exactly that many bits |
u8 u16 u32 u64 | unsigned integers of exactly that many bits |
iw uw | signed and unsigned integers as wide as a pointer: 32 bits on wasm, 64 bits on the native Linux targets |
f32 f64 | floating-point numbers (IEEE 754) |
bool | true or false |
char | one Unicode code point, stored in 32 bits |
type | a type, used as a value |
any | a value of any type |
Vyi has no int. Every integer type states its width. i32 is the usual
choice, and it's the type a plain integer literal gets when nothing else
decides.
No automatic conversions
One number type never mixes with another unless you convert it, even when the
conversion couldn't lose anything. Adding an i32 to an i64 is an error:
fn main() !u8 {
con count: i32 = 3
con total: i64 = 1000
con sum = count + total // error: this operand of `+` has type i64, where i32 is expected
return Ok(0)
}Convert one side to make the types match:
import { println } from "@fmt"
fn main() !u8 {
con count: i32 = 3
con total: i64 = 1000
con sum = i64(count) + total
println(sum) // prints 1003
return Ok(0)
}So every change of width or sign in a program is visible in its source. There are no promotion rules to memorize.
Integer overflow
+, -, and * on integers give the exact result when it fits the type.
When it doesn't, the result depends on the build mode:
- A debug build stops the program with
panic: integer overflow. Debug is the default. - A release build (
--mode release) wraps the result around at the type's width.
When wrapping is what you want, use +%, -%, and *%. They wrap in every
build mode (guide 13). The
build modes reference covers
the modes in full.
Some operations panic in every build mode, and some only in debug:
- Dividing by zero with
/or%panics withdivision by zero, in every build mode. - In a debug build, shifting by a count that is negative or not less than the operand's width panics with
shift count out of range.
Characters
A char holds one Unicode code point in 32 bits. It isn't a u8, because a
character of text and a byte of memory are different things: one character
can take up to four bytes once it's encoded as UTF-8. char has no arithmetic.
To get a character's number, or to turn a number back into a character,
convert it:
import { println } from "@fmt"
fn main() !u8 {
con letter = 'A'
con smile = '😀' // one char, 4 bytes in UTF-8
println(letter) // prints A
println(u32(letter)) // prints 65
println(char(66)) // prints B
return Ok(0)
}Types as values
type is in the table because types are values in Vyi. A type can be stored
in a binding and used wherever a type is expected:
con Count: type = i32
con apples: Count = 5The unit type ()
A function that returns nothing returns (), the empty tuple. Vyi has no
void. () is an ordinary type with exactly one value, also written ():
import { println } from "@fmt"
fn greet() { // no return type means ()
println("hello")
}
fn greetAgain() () { // the same thing, written out
println("hello again")
return ()
}
fn main() !u8 {
greet() // prints hello
con u = greetAgain() // prints hello again
return Ok(0)
}u holds the value ().
Because () is an ordinary type, it fits wherever a type is needed. For
example, ()!T is a result whose error case carries no data (guide
07).
Literals
Integers
Write integers in decimal, hexadecimal (0x), binary (0b), or octal (0o).
An underscore can separate digits to make long numbers easier to read:
import { println } from "@fmt"
fn main() !u8 {
println(1_000_000) // prints 1000000
println(0xFF) // prints 255
println(0b1010) // prints 10
println(0o17) // prints 15
return Ok(0)
}An integer literal takes whatever integer type the code around it needs. With
nothing to decide, it's an i32:
fn double(n: i64) i64 { return n * 2 }
fn main() !u8 {
con a = 7 // nothing decides: i32
con b: i64 = 7 // the declared type decides: i64
con c = double(7) // the parameter type decides: i64
con d = u8(7) // the conversion decides: u8
return Ok(0)
}A literal that doesn't fit its type is a compile error. It never wraps:
con level: u8 = 300 // error: integer literal 300 overflows u8Floats
A number with a decimal point is a float. With nothing to decide, it's an
f64. Declare or convert to get an f32. Like the integer types, f32 and
f64 never mix without a conversion:
con half = 0.5 // f64
con scale: f32 = 1.5 // f32: the declared type decides
con doubled = scale * f32(2) // both sides are f32Booleans
The booleans are true and false. !, &&, ||, and the condition of an
if take a bool. An integer is not a boolean: write n != 0, not n.
Characters
A character literal uses single quotes and holds one code point. These escapes are available:
| Escape | Meaning |
|---|---|
\n \r \t | newline, carriage return, tab |
\0 | the code point 0 |
\\ \' \" | a backslash, a single quote, a double quote |
\xHH | the code point with hex value HH, from 00 to FF |
\u{H…} | the code point with hex value H…, any code point |
con nl = '\n'
con hex = '\x41' // 'A'
con uni = '\u{1F600}' // '😀'Strings
A string literal uses double quotes. Its text is stored in the program as UTF-8
bytes, and its type is [*con]u8: a read-only view of a run of bytes, with a
length.
A string is made of bytes, not characters. Indexing a string gives a u8, and
.len counts bytes. A character outside ASCII takes more than one byte:
import { println } from "@fmt"
fn main() !u8 {
con word = "héllo"
println(word.len) // prints 6
println(word[0]) // prints 104
return Ok(0)
}é takes two bytes, so the five characters of "héllo" take six bytes.
word[0] is the byte for h, 104.
Strings take the same escapes as characters, with one difference: in a string,
\xHH is a single byte with that value, and \u{…} is the UTF-8 bytes of the
code point.
No null
Vyi has no null. A value that may be absent has the optional type ?T, and
the absent case is None. None is an ordinary enum variant, not a keyword.
Guide 07 covers optionals.
Converting between types
A conversion looks like a function call named after the target type:
u8(x), f64(n), char(code). Conversions work between the number types and
char, and they take effect exactly where you write them:
- Converting an integer to a narrower integer type keeps the low bits, so it wraps.
- Converting a float to an integer drops the fractional part, rounding toward zero.
import { println } from "@fmt"
fn main() !u8 {
con big: i32 = 300
println(u8(big)) // prints 44
println(i32(2.9)) // prints 2
println(i32(-2.9)) // prints -2
return Ok(0)
}A u8 holds 0 to 255, so 300 wraps around to 300 - 256, which is 44.
The two rules work together. A literal that doesn't fit its type is an error, because the compiler can see the mistake. Converting a value to a narrower type wraps, because writing the conversion says you meant it. Since nothing converts on its own, a written conversion is the only place a value can change its range:
con level: u8 = 7
con score: i32 = level // error: this value has type u8, but the binding is declared i32Write i32(level) to widen it.
The types reference and the lexical reference give the complete rules.