“借来的价值活得不够久"使用 as_slice() 时 [英] "borrowed value does not live long enough" when using as_slice()

查看:25
本文介绍了“借来的价值活得不够久"使用 as_slice() 时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个错误:

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

对我来说,代码不会出错.为什么我会遇到这个错误?

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

推荐答案

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

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

这篇关于“借来的价值活得不够久"使用 as_slice() 时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆