How to transfer ownership during iteration?

Viewed 71

I have this working code:

let foo_ips = vec![Ipv4Addr::new(127,0,0,1),
                   Ipv4Addr::new(127,0,0,2),
                   Ipv4Addr::new(127,0,0,3)];

let foos: Vec<Foo> = foo_ips.iter().map(|x| {Foo::new(*x)}).collect();

I believe that this is using a copy constructor to create new Ipv4Addrs to pass to Foo::new().

Am I correct?

If so, how do I take the ips out of foo_ips to pass ownership of each to Foo::new()?

1 Answers

into_iter(), instead of iter(), will consume the vector.

Note that Ipv4Addr is so small (32 bits) that it is Copy (nothing to be gained if we move instead of copying).

use std::net::Ipv4Addr;

#[derive(Debug)]
struct Foo(Ipv4Addr);

impl Foo {
    fn new(addr: Ipv4Addr) -> Self {
        Foo(addr)
    }
}

fn main() {
    println!("size of Ipv4Addr: {}", std::mem::size_of::<Ipv4Addr>());

    let foo_ips = vec![
        Ipv4Addr::new(127, 0, 0, 1),
        Ipv4Addr::new(127, 0, 0, 2),
        Ipv4Addr::new(127, 0, 0, 3),
    ];

    let engines: Vec<Foo> = foo_ips.iter().map(|x| Foo::new(*x)).collect();
    println!("engines: {:?}", engines);
    println!("foo_ips: {:?}", foo_ips); // still available

    let engines: Vec<Foo> =
        foo_ips.into_iter().map(|x| Foo::new(x)).collect();
    println!("engines: {:?}", engines);
    // println!("foo_ips: {:?}", foo_ips); // consumed!
}
Related