"借来的价值不够活跃"当使用as_slice()时

时间:2014-10-30 14:32:29

标签: rust borrow-checker

我遇到了一个错误:

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);
}

错误:

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

对我来说,代码没有错。为什么我有这个错误?

1 个答案:

答案 0 :(得分:16)

这里的问题是你没有将from_base64的结果存储在任何地方,然后通过调用as_slice来引用它。链接这样的调用会导致from_base64的结果超出行尾的范围,并且所引用的引用不再有效。

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());
}