Untitled
Anonymous
Plain Text
08/20/2025 10:08 AM
1.2 KB
10
Indexable
Never
use std::mem::size_of;
#[derive(Debug)]
struct Point {
x: i64,
y: i64,
}
fn borrow_point(p: &Point) {
println!("borrow_point(): got {:?}", p);
}
fn take_box_and_return(b: Box<Point>) -> Box<Point> {
println!("take_box_and_return(): got {:?}", b);
b // return ownership
}
fn main() {
println!("Heap Allocation with Box");
// Point on stack
let p_stack = Point { x: 0, y: 0 };
println!("Point on stack: {:?}, size: {} bytes", p_stack, size_of::<Point>());
// Point on heap with Box
let mut p_box = Box::new(Point { x: 1, y: 2 });
println!("Box<Point> (pointer) size on stack: {} bytes", size_of::<Box<Point>>());
println!("*p_box = {:?}", *p_box);
p_box.x += 10;
println!("After mutation: *p_box = {:?}", *p_box);
// Double indirection: Box<Box<Point>>
let pp = Box::new(Box::new(Point { x: 9, y: 9 }));
println!("Double Box size on stack: {} bytes", size_of::<Box<Box<Point>>>());
println!("**pp = {:?}", **pp);
// Borrow vs move
borrow_point(&p_stack); // borrow stack value
borrow_point(&p_box); // borrow heap value
// Move ownership into function and return it
let p_box = take_box_and_return(p_box);
println!("Back in main: {:?}", *p_box);
}Editor is loading...
Leave a Comment