gpt4 book ai didi

rust - 使用 `let` 绑定(bind)来增加值的生命周期

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

我写了下面的代码来从 stdin 中读取一个整数数组:

use std::io::{self, BufRead};

fn main() {
let stdin = io::stdin();
for line in stdin.lock().lines() {
let xs: Vec<i32> = line.unwrap()
.trim()
.split(' ')
.map(|s| s.parse().unwrap())
.collect();

println!("{:?}", xs);
}
}

这很好用,但是,我觉得 let xs 行有点长,所以我把它分成两部分:

use std::io::{self, BufRead};

fn main() {
let stdin = io::stdin();
for line in stdin.lock().lines() {
let ss = line.unwrap().trim().split(' ');
let xs: Vec<i32> = ss.map(|s| s.parse().unwrap()).collect();

println!("{:?}", xs);
}
}

这没用! Rust 回复了以下错误:

error[E0597]: borrowed value does not live long enough
--> src/main.rs:6:18
|
6 | let ss = line.unwrap().trim().split(' ');
| ^^^^^^^^^^^^^ - temporary value dropped here while still borrowed
| |
| temporary value does not live long enough
...
10 | }
| - temporary value needs to live until here
|
= note: consider using a `let` binding to increase its lifetime

这让我很困惑。是line还是ss活的不够长?我如何使用 let 绑定(bind)来延长它们的生命周期?我以为我已经在使用 let 了?

我已经通读了 lifetime guide ,但我还是不太明白。谁能给我一个提示?

最佳答案

在您的第二个版本中,ss 的类型是 Split<'a, char> .类型中的生命周期参数告诉我们该对象包含一个引用。为了使赋值有效,引用必须指向该语句之后存在的对象。然而, unwrap() 消耗 line ;换句话说,它移动了 Ok Result 中的变体数据目的。因此,引用不指向原始 line 内部,而是在临时对象上。

在您的第一个版本中,您通过调用 map 来消耗长表达式末尾的临时值。 .要修复您的第二个版本,您需要绑定(bind) unwrap() 的结果使值(value)保持足够长的时间:

use std::io::{self, BufRead};

fn main() {
let stdin = io::stdin();
for line in stdin.lock().lines() {
let line = line.unwrap();
let ss = line.trim().split(' ');
let xs: Vec<i32> = ss.map(|s| s.parse().unwrap()).collect();

println!("{:?}", xs);
}
}

关于rust - 使用 `let` 绑定(bind)来增加值的生命周期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26080157/

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