首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在Rust中的多个向量中有一个结构实例

在Rust中的多个向量中有一个结构实例
EN

Stack Overflow用户
提问于 2019-02-22 04:51:44
回答 1查看 78关注 0票数 1

我正在用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

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

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-02-22 05:02:50

最简单的方法是克隆container_details

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

这需要shiplift::rep::ContainerDetails实现Clone,根据it's docs的说法,它确实实现了。

这确实有一些缺点:

  1. 将内存使用量增加了一倍(但由于它称为详细信息,我假设它不会使用那么多内存,container_details中的项不会反映在克隆的版本中。

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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54816025

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档