Consider the following piece of code:
struct MyRectangle { x: i32, y: i32, length: i32, breadth: i32, } fn allocate_rect() { let x: Box<MyRectangle> = Box::new (MyRectangle {x: 5, y: 5, length: 25, breadth:15}); }
The x variable is the single owner of the my_rectangle object on the heap. As soon as allocate_rect() is complete, the memory on the heap allocated to x is freed, since the last owner is gone.
The single owner is enforced by the compiler. The following example demonstrates transferring ownership. Once the transfer is complete, the original cannot be used again:
fn swap_around() { let my_rect: Box<MyRectangle> = Box::new(MyRectangle{x:5, y:5, length:25, breadth:15}); let dup_rect = my_rect; // dup_rect is now the owner println!("{}", dup_rect.x); println!("{}", my_rect.x); // won't work - use of moved value }