【问题标题】:"borrowed value does not live long enough" when using as_slice()使用 as_slice() 时“借来的值不够长”
【发布时间】:2014-12-26 15:45:43
【问题描述】:

我遇到了一个错误:

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

不过,对我来说,代码不会出错。为什么我会出现这个错误?

【问题讨论】:

  • 请注意,let a: [u8, ..30] = [ 123, 34, ... ]; 可能很麻烦,因为您必须在更改数组时调整长度。如果你想记录长度,这很好,如果你不需要它并且感到痛苦,还有另一种表达方式:let a = [123u8, 34, ...];。关键是12334 只是泛型积分(没有特定类型),因此您通过指定u8 来约束它们;然而,由于数组是同质容器,另一种解决方案是限制一个容器的类型(第一个,通常是123u8),编译器推断所有都是u8

标签: rust borrow-checker


【解决方案1】:

这里的问题是您没有将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());
}

【讨论】:

  • The problem here is that you are not storing the result of from_base64 anywhere and then take a reference to is by calling as_slice - 为什么?我几乎可以用任何其他编程语言做到这一点,而且它会起作用。
  • 这是目前的情况,RFC31 会解决这个问题。
  • 所以即使 a.from_base64() 没有改变 a 并产生一个新变量,它现在在 Rust 中还没有?
  • 它与a 没有任何联系,只是您引用了from_base64 的结果,这是临时的,因为它没有存储在任何地方。
猜你喜欢
  • 1970-01-01
  • 2020-07-23
  • 1970-01-01
  • 1970-01-01
  • 2015-04-12
  • 2019-11-29
  • 1970-01-01
  • 2016-09-20
  • 1970-01-01
相关资源
最近更新 更多