Module mem

mem
Stability: unstable — may still change; see below.

Moving a value out of a place that stays alive: replace, take and swap (Rust's std::mem).

A field of a move-only or explicit-copy value cannot be moved out of a holder that stays alive (plans/VALUES_BY_DEFAULT.md decision 19, "no partial moves"). These three functions are the way out without a copy: each moves the old contents out bitwise and something else in, so the place is never empty and nothing is copied or dropped twice.

{ replace, take } :: import("std/mem");
{ ArrayList } :: import("std/collections/array_list");
{ String } :: import("std/string");
Job :: struct(name : String, log : ArrayList(String));
(mut(job) : Job) = Job(name : `build`, log : ArrayList(String).new());
job.log.push(`started`);
done := take(&mut job.log); // `job.log` is a new empty list
old := replace(&mut job.name, `test`); // `build`

A unit place has no C storage; the three functions accept it all the same (its only value is (), so nothing moves).

Stability

unstable — decision 19's spelling (V2b B6-0). The names follow Rust's std::mem and live in their own module rather than the prelude, because a prelude export reserves its name in every module.

Functions

replace function
fn(generic(T : Type), dst : &mut T, v : T) -> T

Store v in dst and return the value it replaces — Rust's mem::replace. Neither value is copied or dropped.

{ replace } :: import("std/mem");
(mut(x) : i32) = i32(1);
old := replace(&mut x, i32(2));
assert((old == i32(1)) && (x == i32(2)), "replace hands back the old value");

Type Parameters

NameTypeNotes
TTypecomptime

Parameters

NameTypeNotes
dst&mut T
vT

Returns: T

take function
fn(generic(T : Type), dst : &mut T, where(T <: Default)) -> T

Store T's default in dst and return the value it replaces — Rust's mem::take.

{ take } :: import("std/mem");
{ ArrayList } :: import("std/collections/array_list");
(mut(xs) : ArrayList(i32)) = ArrayList(i32).new();
xs.push(i32(1));
ys := take(&mut xs);
assert((ys.len() == usize(1)) && (xs.len() == usize(0)), "take leaves the default");

Type Parameters

NameTypeNotes
TTypecomptime

Parameters

NameTypeNotes
dst&mut T

Returns: T

swap function
fn(generic(T : Type), a : &mut T, b : &mut T) -> unit

Exchange the values of a and b — Rust's mem::swap. Neither value is copied or dropped.

{ swap } :: import("std/mem");
(mut(a) : i32) = i32(1);
(mut(b) : i32) = i32(2);
swap(&mut a, &mut b);
assert((a == i32(2)) && (b == i32(1)), "swap exchanges the values");

Type Parameters

NameTypeNotes
TTypecomptime

Parameters

NameTypeNotes
a&mut T
b&mut T

Returns: unit