Indexing A Vec Cannot Move Values Out

Indexing yields a place, not a movable value: Copy fields read directly, while mem::take, swap_remove, and remove each hand ownership back.

RustData Integrity

Code

rustsnippet
32 lines
#[derive(Debug)]
struct Host {
    name: String,
    port: u16,
}

fn main() {
    let mut hosts = vec![
        Host { name: "eu-1".into(), port: 8080 },
        Host { name: "us-1".into(), port: 9090 },
    ];

    // Indexing yields a place, not a movable value: Copy fields read directly
    let port = hosts[0].port;
    println!("port: {port}");

    // hosts[0].name would try to move out of a borrow - not allowed.
    // Three escape hatches hand the value back instead:

    // 1. mem::take swaps in a default and returns the old String
    let taken = std::mem::take(&mut hosts[0].name);
    println!("taken: {taken} (slot now holds an empty String)");

    // 2. swap_remove returns the element and fills the hole with the last one
    let swapped = hosts.swap_remove(0);
    println!("swapped: {:?}", swapped);

    // 3. remove keeps order but shifts the tail left
    let removed = hosts.remove(0);
    println!("removed: {:?}", removed);
    println!("left: {:?}", hosts);
}

The mechanics of this demo — Indexing A Vec Cannot Move Values Out

The code’s whole job belongs to the function main.

What to watch for

  • Only the runtime itself is required; packages and installers stay out of it.

Putting it to use

The entry-point signature is fn main()

The run emits 5 labeled sections — port:, taken:, swapped:, removed:, left: — one per step.

Core lines

let taken = std::mem::take(&mut hosts[0].name);
let swapped = hosts.swap_remove(0);
let removed = hosts.remove(0);

Interactive Tools for This Topic

FAQ

What does Indexing A Vec Cannot Move Values Out print when run?
Running the file directly is enough — expect labeled output lines such as `port:`, `taken:`, `swapped:`.