Skip to content

Values and types

let names a value. It cannot change unless you say let mut.

let name = "Ada"
let mut count = 1
count += 1
count *= 10
print(f"{name} {count}")
Ada 20

Types are inferred, and you can write them when you want to: let ratio: f64 = 0.5.

i64 is the everyday integer. There are also i8, i16, i32, u8, u16, u32, u64, and the floats f64 and f32. Brass never converts between them on its own, and integer overflow stops the program instead of wrapping silently. Converting is explicit. to_u8(), to_f64() and the like stop the program if the value does not fit; the _checked forms give an Option instead, for values that come from outside:

let big: i64 = 200
let small = big.to_u8()
print(f"{small} {7 / 2} {7.0 / 2.0} {2.0.pow(10.0)} {big.to_f64() / 3.0}")
let port: i64 = 70000
print(port.to_u16_checked())
print(big.to_u16_checked())
200 3 3.5 1024.0 66.66666666666667
None
Some(200)

print and f-strings show numbers, text, bool, Option, Vec and tuples, and any type with a to_str(&self) -> Str method.

Str is UTF-8 text. It has the usual methods (len, trim, split, find, replace, starts_with, strip_prefix, split_once, …). len() counts bytes; codepoints() and graphemes() count characters.

let line = " key = some value "
match line.trim().split_once(" = ") {
Some((key, value)) => print(f"[{key}] [{value}]")
None => print("not a setting")
}
print("ok".pad_start(5, "."))
print("é".len().to_str() + " " + "é".codepoints().len().to_str())
[key] [some value]
...ok
2 1

An f-string puts values into text: f"{x}", with formatting such as f"{price:.2}" or f"{n:05}".

Longer text goes between """ lines. The indentation of the closing """ is removed from every line, so the text lines up with the code. r"..." is a raw string, where \ is just a backslash:

let user = "Ada"
let count = 3
let letter = f"""
Dear {user},
your {count} orders have shipped.
"""
print(letter)
print(r"\d+\.\d+")
Dear Ada,
your 3 orders have shipped.
\d+\.\d+

A value that may be missing is an Option: Some(value) or None. There is no null, so the compiler makes you deal with the None case.

let words = ["apple", "kiwi"]
match words.first() {
Some(w) => print("first: " + *w)
None => print("empty")
}
let n = "42".to_i64().unwrap_or(0)
print(f"{n + 1}")
first: apple
43