← 中文资源

简体中文版本

Vec 下标取值需要 take 与 remove

对 Vec 下标只能得到位置,不能移出非 Copy 字段:mem::take 换入默认值,swap_remove 与 remove 各自以不同代价归还所有权。

阅读英文原文

实现说明

Vec 下标取值需要 take 与 remove以函数 main为骨架。

使用要点

  • 直接运行文件,输出会带上标签,比如 port:、taken:、swapped:——输出的每一行都能指回产生它的那次调用。

常见问题

运行「Vec 下标取值需要 take 与 remove」会打印什么?

不用做任何设置,直接把文件跑完——输出里的 port:、taken:、swapped: 标签标明各步骤。

核心语句

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

代码示例

#[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);
}