Push a struct into a vec and pass its reference within a loop

I'm struggling to figure out how to iterate over a collection of structs, and, within the loop, push the struct into a new vec and pass its reference to another struct. It's a hard problem to put words to, so here's some example code that demonstrates the problem:

fn main() {
    works();
    does_not_work();
}

fn works() {
    let original = vec![TestObj::new("a"), TestObj::new("b"), TestObj::new("c")];
    let mut new = Vec::new();

    let mut holder = Holder::new();

    for object in original {
        new.push(object);
    }

    for object in new.iter() {
        holder.hold(object);
    }

    println!("{:#?}", new);
    println!("{:#?}", holder);
}

fn does_not_work() {
    let original = vec![TestObj::new("a"), TestObj::new("b"), TestObj::new("c")];
    let mut new = Vec::new();

    let mut holder = Holder::new();

    for object in original {
        {
            new.push(object);
        }
        holder.hold(new.last().unwrap());
    }

    println!("{:#?}", new);
    println!("{:#?}", holder);
}

#[derive(Debug)]
struct TestObj {
    foo: String,
}

#[derive(Debug)]
struct Holder<'a> {
    objects: Vec<&'a TestObj>,
}

impl TestObj {
    fn new(foo: &str) -> Self {
        Self {
            foo: foo.to_owned()
        }
    }
}

impl<'a> Holder<'a> {
    fn new() -> Self {
        Self {
            objects: Vec::new(),
        }
    }
    fn hold(&mut self, object: &'a TestObj) {
        self.objects.push(object);
    }
}

In this example, the code in the works function does exactly what I want it to do, with the exception that it requires two iterations. I want to be able to do it in a single iteration.

The code in does_not_work is one attempt at doing so. However, it gets me in trouble with the borrow checker because of the mutable borrow at new.push() and the subsequent immutable borrow at new.last(). I attempted to scope the mutable borrow within a block, but it seems to have no affect.

The other approach I tried was passing the reference before moving the struct into the new vec, but this approach had lifetime issues.

Is there a way to do this without iterating twice?

Probably not. Note that your does_not_work would have UB if written in C++ because whenever new runs out of capacity and reallocates, all of your pointers would become invalidated.

Ah, that makes sense. Thank you!