Hristo Kolev
Hristo Kolev

Reputation: 1574

Having a struct instance in more than one vector in Rust

I'm building an application in Rust that backs up docker volumes.

I wanted to know which containers are using the target volume.

This is the code I use:

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

I'm trying to put all matching containers in a vector. The error that I get is:

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

I know that you can't have the same value in 2 vectors, but how else do I do something like this?

How do I get a "list" of the values that match a given (non trivial condition) ?

Upvotes: 1

Views: 148

Answers (1)

8176135
8176135

Reputation: 4123

The easiest way is to clone container_details:

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

This requires shiplift::rep::ContainerDetails to implement Clone, which according to it's docs, it does.


This does have a few downsides:

  1. Double the memory usage (but since it is called Details, I assume that it doesn't use that much memory anyway).

  2. Changes to items in container_details does not get reflected in the cloned versions.

Having get_container_details return Vec<Rc<ContainerDetails>> instead, then cloning container_detail will only clone a reference.

Upvotes: 2

Related Questions