hd-lang

Tour · 7 of 18

References

The program on the right changes stock through references instead of copies.

#Reading in place

fn units(stock: &Stock) -> i32:
    stock.units

A plain parameter gets a copy. &Stock reads the caller's value without one. Writing through it, such as stock.units = 0, is an error.

#Writing in place

fn restock(stock: &mut Stock, added: i32) -> void:
    stock.units += added

&mut Stock may change the caller's value. The call writes &mut too, as in restock(&mut local, 3). These local references cannot escape the call.

#Stored references

struct SharedStock:
    view: *Stock
    editable: *mut Stock

A field can hold a stored reference. *Stock reads, and *mut Stock also writes. A plain Stock value does not fit such a field.

#Shared objects

shared := box(Stock { units: local.units })

box puts a value in a new shared object and gives a *mut Stock. The object stays alive while a stored reference points to it. Both fields of holder point to it, so a write through editable shows through view.

Run it. It prints local: 2 before the restock. The shared stock starts at 5 and loses 1, so it then prints shared: 4.

Try it: change shared := box(Stock { units: local.units }) to shared := Stock { units: local.units } and press Run.

Run: Ctrl+Enter · Pages: Alt+← Alt+→