gpt4 book ai didi

rust - 使用 as_slice() 时为 "borrowed value does not live long enough"

转载 作者:行者123 更新时间:2023-11-29 07:42:42 25 4
gpt4 key购买 nike

我遇到了一个错误:

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

不过,对我而言,代码不会出错。为什么会出现该错误?

最佳答案

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

关于rust - 使用 as_slice() 时为 "borrowed value does not live long enough",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26655752/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com