开发者

Why error "temporary value dropped while borrowed" occurs in only one of two quite similar pieces of Rust code? [duplicate]

开发者 https://www.devze.com 2022-12-07 20:33 出处:网络
This question already has an answer here: Why can I return a reference to a local literal but not a variable?
This question already has an answer here: Why can I return a reference to a local literal but not a variable? (1 answer) Closed 3 hours ago.

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 bs value into it.

0

精彩评论

暂无评论...
验证码 换一张
取 消