struct Point {
x: i32,
y: i32
}
fn main() {
let point = Point { x: 1, y: 1};
}
Rust defaults to allocation on the stack
struct Point {
x: i32,
y: i32
}
fn main() {
let point = Point { x: 1, y: 1};
}
Heap allocation is represented by the type Box
.
struct Point {
x: i32,
y: i32
}
fn main() {
let point = Point { x: 1, y: 1};
let point_on_heap = Box::new(point);
}
Box
is owned, but you can borrow the contained values.
#[derive(Debug)]
struct Point {
x: i32,
y: i32
}
fn main() {
let point = Point { x: 1, y: 1};
let point_on_heap = Box::new(point);
print_point(&point_on_heap);
}
fn print_point(p: &Point) {
println!("{:?}", p);
}
Other types also allocate on the heap, most notably Vec
and String
.
It is currently not possible to allocate values at a self-chosen location. The missing feature is called "placement in".
In most cases, LLVM already optimizes the stack allocation and the subsequent move to the heap to a direct heap allocation.