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
?