Ownership
Brass frees memory without a garbage collector. It does this by knowing, at compile time, who owns each value.
- Every value has one owner. Assigning it or passing it by value moves it: the old name can no longer be used.
&valuelends it for reading,&mut valuelends it for changing. The owner keeps it.- When the owner goes out of scope, the value is freed.
Small plain values (numbers, bool, references, and structs made only of
those) are copied instead of moved, so this mostly matters for Str,
Vec, Map and the like.
let a = "some text"let b = aprint(a)`a` was movedBorrow instead, or make a copy on purpose with clone():
fn count_words(text: &Str) -> i64 { return text.words().len()}
fn add_signature(text: &mut Str) { text.push("\n-- sent from Brass")}
let mut letter = "Dear reader, hello."print(f"{count_words(&letter)} words")add_signature(&mut letter)let copy = letter.clone()print(copy)print(f"{letter.len() == copy.len()}")3 wordsDear reader, hello.-- sent from BrasstrueThere is no lifetime syntax. A function can return a reference only into one of its parameters, and the compiler checks that a borrowed value lives as long as the reference to it is used:
let mut names = ["a", "b"]let first = &names[0]names.push("c")print(*first)cannot change, move or mutably borrow `names` while `first` borrows itCleanup with Drop
Section titled “Cleanup with Drop”A type can run code when it is freed by implementing Drop. The standard
library uses this for temporary folders, open processes and connections.
The compiler runs drop exactly once, on every path out of the scope.
struct Timer { label: Str}
impl Drop for Timer { fn drop(&mut self) { print("done: " + self.label) }}
fn work() { let _t = Timer { label: "work" } print("working")}
work()print("after")workingdone: workafterSome values must not simply be dropped: a started process should be waited
for, a transaction committed or rolled back. Types marked with
impl Finish for T {} must be handed to a method that consumes them on
every path, or the program does not compile.