I have the following code snippet:
extern crate debug; use std::mem::size_of_val; struct A<'a> { a: &'a [i64], } fn main() {
When I define a slice with & (ie &[1, 2, 3] ), as in the following println!
println!("{} - {:?}", size_of_val(&A { a: &[1, 2, 3] }), A { a: &[1, 2, 3] });
conclusion
16 - A<'static>{a: &[1i64, 2i64, 3i64]}
Determination of cut-off without &
println!("{} - {:?}", size_of_val(&A { a: [1, 2, 3] }), A { a: [1, 2, 3] });
gives the same result
16 - A<'static>{a: &[1i64, 2i64, 3i64]}
If I first try to bind an instance of struct A whose field A initialized with a slice reference (i.e. using & ) to the variable x
let x = A { a: &[1, 2, 3] };
and I'm trying to do a similar println! like previous
println!("{} - {:?}", size_of_val(&x), x);
I get
16 - A<'static>{a: &[1i64, 2i64, 3i64]}
However, if I bind an instance of A whose field A initialized with a slice (not a reference to the slice using & ), the variable x
let x = A { a: [1, 2, 3] };
and I'm trying to do a similar println! like previous
println!("{} - {:?}", size_of_val(&x), x);
I get the following build error:
/prpath/main.rs:12:20: 12:29 error: borrowed value does not live long enough /prpath/main.rs:12 let x = A { a: [1 ,2, 3] }; ^~~~~~~~~ /prpath/main.rs:11:11: 15:2 note: reference must be valid for the block at 11:10... /prpath/main.rs:11 fn main() { /prpath/main.rs:12 let x = A { a: [1 ,2, 3] }; /prpath/main.rs:13 /prpath/main.rs:14 println!("{} - `{:?}`", size_of_val(&x), x); /prpath/main.rs:15 } /prpath/main.rs:12:5: 12:31 note: ...but borrowed value is only valid for the statement at 12:4; consider using a `let` binding to increase its lifetime /prpath/main.rs:12 let x = A { a: [1 ,2, 3] }; ^~~~~~~~~~~~~~~~~~~~~~~~~~ error: aborting due to previous error
I expected that only the definition of A { a: &[1, 2, 3] } was allowed, because Aa should be of type &[i64] , but Rust seems to let us not include the & character.
What is the difference between A { a: &[1, 2, 3] } and A { a: [1, 2, 3] } ? Why are we allowed to use A { a: [1, 2, 3] } (in the second example above)?