我遇到了一个错误:
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, ...];
关键在于123
和34
只是通用的整数(没有具体类型),所以通过指定u8
来限制它们;然而,由于数组是同质容器,另一种解决方案是限制其中一个元素的类型(通常是第一个元素,即123u8
),编译器会推断出所有元素都是u8
! - Matthieu M.