Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

rust - "borrowed value does not live long enough" when using as_slice()

I ran into an error:

extern crate rustc_serialize; // 0.3.24

use rustc_serialize::base64::{self, FromBase64, ToBase64};

fn main() {
    let a: [u8; 30] = [0; 30];
    let b = a.from_base64().unwrap().as_slice();
    println!("{:?}", b);
}

The error:

error[E0597]: borrowed value does not live long enough
 --> src/main.rs:7:13
  |
7 |     let b = a.from_base64().unwrap().as_slice();
  |             ^^^^^^^^^^^^^^^^^^^^^^^^           - temporary value dropped here while still borrowed
  |             |
  |             temporary value does not live long enough
8 |     println!("{:?}", b);
9 | }
  | - temporary value needs to live until here
  |
  = note: consider using a `let` binding to increase its lifetime

For me, the code can do no wrong, though. Why am I having that error?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The problem here is that you are not storing the result of from_base64 anywhere and then take a reference to it by calling as_slice. Chaining calls like that causes the result of from_base64 to go out of scope at the end of the line and the reference taken is no longer valid.

extern crate rustc_serialize; // 0.3.24

use rustc_serialize::base64::FromBase64;

fn main() {
    let a: [u8; 30] = [0; 30];
    let b = a.from_base64().unwrap();
    println!("{:?}", b.as_slice());
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...