I'm learning about reference and slice in Rust so trying to write some random code:
fn main() {
let a = &[&[2]][..];
println!("{:?}", a); // OK
let b = 2;
let c = &[&[b]][..];
println!("{:?}", c);
// error[E0716]: temporary value dropped while borrowed
// --> src/main.rs:6:16
// |
// 6 | let c = &[&[b]][..];
// | ^^^ - temporary value is freed at the end of this statement
// | |
// | creates a temporary which is freed while still in use
// 7 | println!("{:?}", c);
// | - borrow later used here
// |
// help: consider using a `let` binding to create a longer lived value
// |
// 6 ~ let binding = [b];
// 7 开发者_高级运维~ let c = &[&binding][..];
// |
// For more information about this error, try `rustc --explain E0716`.
// error: could not compile `playground` due to previous error
}
I don't know why changing &[2]
to &[b]
got above error? Please explain for me about this.
As a newbie, it's pretty hard for me to explain my problem more clearly. So sorry guys!!
The pieces while looking similar are in fact quite different:
A static array like [2]
is something the compiler can and will put into the binary.
An array created from a local variable [b]
has to be dynamically created at runtime by copying b
s value into it.
精彩评论