我有以下的代碼:「借用值不活得足夠長的」使用與切片一個結構時
extern crate debug;
use std::mem::size_of_val;
struct A<'a> {
a: &'a [i64],
}
fn main() {
// code
}
當我定義與切片&
(即&[1, 2, 3]
)如以下println!
println!("{} - {:?}", size_of_val(&A { a: &[1, 2, 3] }), A { a: &[1, 2, 3] });
輸出是
16 - A<'static>{a: &[1i64, 2i64, 3i64]}
d efining切片而不&
println!("{} - {:?}", size_of_val(&A { a: [1, 2, 3] }), A { a: [1, 2, 3] });
給我相同的結果
16 - A<'static>{a: &[1i64, 2i64, 3i64]}
如果我第一嘗試綁定一個struct A
,其a
字段與到的切片的引用初始化的實例(即使用&
),一個變量x
let x = A { a: &[1, 2, 3] }; // &[1, 2, 3] is a reference to a slice
,我試圖執行一個類似的println!
作爲以前的
println!("{} - {:?}", size_of_val(&x), x);
我得到
16 - A<'static>{a: &[1i64, 2i64, 3i64]}
但是,如果我綁定一個實例的A
,其a
字段被初始化爲片(不是使用的片的引用),一個變量x
let x = A { a: [1, 2, 3] };
,我試圖執行一個類似的println!
作爲以前的
println!("{} - {:?}", size_of_val(&x), x);
我得到下面的生成錯誤:
/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
我期待只有A { a: &[1, 2, 3] }
定義被允許,因爲A.a
應該有&[i64]
類型,但顯然, Rust允許我們不包含&
符號。
A { a: &[1, 2, 3] }
和A { a: [1, 2, 3] }
有什麼區別?爲什麼我們允許使用A { a: [1, 2, 3] }
(在上面的第二個例子中)?