Skip to content
The Chat Archive
claude-sonnet-4-20250514· Anthropic LMArena Human Preference 140K

Do sending a Vec through a channel in rust copies its content in memory ?

  1. User

    Do sending a Vec through a channel in rust copies its content in memory ?

  2. Assistant

    No, sending a Vec through a channel in Rust does not copy its content in memory. When you send a Vec through a channel, ownership of the vector is transferred (moved) to the receiving end, but the actual heap-allocated data that the Vec points to is not copied.

    Here's what actually happens:

    use std::sync::mpsc;
    
    let (tx, rx) = mpsc::channel();
    let my_vec = vec![1, 2, 3, 4, 5]; // Data lives on the heap
    
    tx.send(my_vec).unwrap(); // Only the Vec struct itself is copied/moved
    // my_vec is no longer accessible here
    
    let received_vec = rx.recv().unwrap(); // Same heap data, new owner
    

    The Vec struct itself is small (typically 24 bytes on 64-bit systems) and contains just a pointer to the heap data, the length, and the capacity. When sent through a channel, only this small struct is copied, while the actual vector elements remain in the same location on the heap.

    This is one of the key benefits of Rust's ownership system - you get efficient transfers of large data structures without expensive deep copies. If you needed the original Vec to remain usable after sending, you'd need to explicitly clone it with .clone(), which would then perform a deep copy of the heap data.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.