【问题标题】:Having a struct instance in more than one vector in Rust在 Rust 的多个向量中拥有一个结构实例
【发布时间】:2019-02-21 20:51:44
【问题描述】:

我正在用 Rust 构建一个备份 docker 卷的应用程序。

我想知道哪些容器正在使用目标卷。

这是我使用的代码:

let volume = await!(get_volume_by_name(&docker, &volume_name));
let container_details = await!(get_container_details(&docker));
let mut connected_containers = Vec::new();

for container_detail in container_details {
    for mount in container_detail.mounts {
        if mount.destination == volume.mountpoint {
            connected_containers.push(container_detail);
        }
    }
}

我正在尝试将所有匹配的容器放入一个向量中。我得到的错误是:

error[E0382]: use of moved value: `container_detail`
  --> src/main.rs:32:43
   |
29 |     for container_detail in container_details {
   |         ---------------- move occurs because `container_detail` has type `shiplift::rep::ContainerDetails`, which does not implement the `Copy` trait
...
32 |                 connected_containers.push(container_detail);
   |                                           ^^^^^^^^^^^^^^^^ value moved here, in previous iteration of loop

我知道你不能在 2 个向量中具有相同的值,但我该怎么做这样的事情呢?

如何获得与给定(非平凡条件)匹配的值的“列表”?

【问题讨论】:

  • 你想在每个向量中存储一个单独的实例,还是存储对同一个实例的引用?

标签: rust


【解决方案1】:

最简单的方法是克隆container_details

if mount.destination == volume.mountpoint {
   connected_containers.push(container_detail.clone());
}

这需要shiplift::rep::ContainerDetails 实现Clone,根据it's docs,它确实如此。


这确实有一些缺点:

  1. 内存使用量翻倍(但由于它被称为详细信息,我假设它不会使用那么多内存)。

  2. container_details 中项目的更改不会反映在克隆版本中。

get_container_details 返回Vec<Rc<ContainerDetails>>,然后克隆container_detail 只会克隆一个引用。

【讨论】:

  • “但既然它被称为Details,我认为它无论如何都不会使用那么多内存”,有趣的是,我虽然“但它被称为Details,它可能很大!”实际上,如果您查看该结构中的字段数量,就会发现它非常庞大。
猜你喜欢
  • 1970-01-01
  • 2019-12-06
  • 1970-01-01
  • 2022-10-23
  • 2020-05-07
  • 2012-06-10
  • 1970-01-01
  • 1970-01-01
  • 2021-08-18
相关资源
最近更新 更多