Rust
Beginner
1 min read
Move Semantics in Depth
Example
#[derive(Debug)]
struct Buffer {
data: Vec<u8>,
}
// Takes ownership of buf — caller can no longer use it
fn process(buf: Buffer) -> usize {
println!("processing {} bytes", buf.data.len());
buf.data.len()
}
// Returns ownership back so the caller can continue using it
fn inspect(buf: Buffer) -> Buffer {
println!("first byte: {:?}", buf.data.first());
buf // move buf back to the caller
}
fn main() {
let buf = Buffer { data: vec![1, 2, 3, 4, 5] };
// Pass to inspect — ownership goes in and comes back
let buf = inspect(buf);
println!("still have buf: {:?}", buf);
// Pass to process — ownership is consumed; buf is gone
let len = process(buf);
// println!("{:?}", buf); // compile error: use of moved value
println!("processed {len} bytes");
// Demonstrate that Vec<u8> is not Copy
let v1 = vec![10u8, 20, 30];
let v2 = v1; // move
// let _ = v1; // compile error
println!("v2 = {:?}", v2);
// Cloning avoids the move
let v3 = v2.clone();
println!("v2={:?} v3={:?}", v2, v3);
}