1

This code:

#[derive(Debug, Clone)]
struct Foo {
    one: u8,
    two: u8,
    v: Vec<u8>,
}

#[derive(Debug, Clone)]
struct Bar {
    alpha: Foo,
    beta: Foo,
}

fn main() -> std::io::Result<()> {
    let foo = Foo {
        one: 1,
        two: 2,
        v: vec![3, 4],
    };

    let bar = Bar {
        alpha: foo,
        beta: foo,
    };

    println!("bar {:?}", bar);

    Ok(())
}

causes the error:

error[E0382]: use of moved value: `foo`
  --> src/main.rs:23:15
   |
15 |     let foo = Foo {
   |         --- move occurs because `foo` has type `Foo`, which does not implement the `Copy` trait
...
22 |         alpha: foo,
   |                --- value moved here
23 |         beta: foo,
   |               ^^^ value used here after move

as foo would have two owners, bar.alpha and bar.beta. Foo cannot implement Copy as it contains a Vec<u8>.

When I make beta a reference:

#[derive(Debug, Clone)]
struct Bar {
    alpha: Foo,
    beta: &Foo,
}
let bar = Bar {
    alpha: foo,
    beta: &foo,
};

I get a more interesting error:

error[E0106]: missing lifetime specifier
  --> src/main.rs:11:11
   |
11 |     beta: &Foo,
   |           ^ expected named lifetime parameter
   |
help: consider introducing a named lifetime parameter
   |
9  | struct Bar<'a> {
10 |     alpha: Foo,
11 |     beta: &'a Foo,
   |

I don't want to introduce a named lifetime parameter.

How do I tell the borrow-checker that beta has the same lifetime as alpha?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
fadedbee
  • 42,671
  • 44
  • 178
  • 308
  • 1
    See also [What is the difference between Copy and Clone?](https://stackoverflow.com/q/31012923/155423); [How do I implement Copy and Clone for a type that contains a String (or any type that doesn't implement Copy)?](https://stackoverflow.com/q/38215753/155423); [What happens when an Arc is cloned?](https://stackoverflow.com/q/40984932/155423). – Shepmaster Jul 07 '20 at 19:29
  • 1
    What would the point be here... why do you _want_ a reference to the field? You already have the field. – Shepmaster Jul 07 '20 at 19:30
  • @Shepmaster Thanks for pointing me at the question I should have asked. (There was a downvote.) – fadedbee Jul 07 '20 at 19:34
  • @Shepmaster It's to do with serde, where a message has "node-details" which need to be in both a "this node" field and in a list of many nodes, including "this node". The code above was just a minimal example of the issue. I'm going to try making everything references next. – fadedbee Jul 07 '20 at 19:36
  • 1
    Serde has [a number of configuration settings](https://serde.rs/field-attrs.html) and [customization points](https://stackoverflow.com/q/39383809/155423). If you can't figure out your specific case, you may wish to ask a new question in the context of Serde. – Shepmaster Jul 07 '20 at 19:43

0 Answers0