我编写了以下代码从 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
绑定来增加它们的生命周期?我以为我已经在使用let
了?
我已经阅读了生命周期指南,但仍然无法完全理解。有人能给我一个提示吗?
CharSplits
引用了line
中的值。但实际上它引用了从Ok
中取出的一个副本,该副本在let ss
行结束时被丢弃。为什么不直接将所有值保持活动状态直到块的末尾呢? - Thomas Ahleline
的变量:第一个是IoResult<String>
(等同于Result<String, IoError>
),第二个是String
。unwrap()
将String
从IoResult
中移出,之后IoResult
就无法再使用了(这也是我在重复使用名称line
的原因:无论如何你都不能再使用第一个line
)。String
根本没有被复制。 - Francis GagnéString
结构体包含一个Vec
,其中包含指向数据(存储在堆上)的指针、长度和容量。当发生移动时,结构体的成员被复制,但引用的数据不会被复制,也不会运行析构函数。原始副本随后由编译器变得无法使用(如果尝试使用该值,则会出现错误),因此您不会访问已转移所有权的数据。 - Francis Gagné