我编写了以下代码来读取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了?

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

推荐答案

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

在第一个版本中,在长表达式的末尾使用临时表达式,尽管调用map.要修复第二个版本,需要绑定unwrap()的结果,以保持该值足够长的生存时间:

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相关问答推荐

使用InlineTables序列化toml ArrayOfTables

当为a Self:IntoIterator设置trait bind `时,获取`a T `不是迭代器"&'"<'>&'

如何在递归数据 struct 中移动所有权时变异引用?

如何正确重新排列代码以绕过铁 rust 借入判断器?

在为第三方 struct 实现第三方特征时避免包装器的任何方法

处理带有panic 的 Err 时,匹配臂具有不兼容的类型

确保参数是编译时定义的字符串文字

实现 Deref 的 struct 可以返回对外部数据的引用吗?

如何强制匹配的返回类型为()?

从 rust 函数返回 &HashMap

为什么切片时需要参考?

Rust 为什么被视为borrow ?

为什么带有生命周期指定的方法不能被调用两次?

为什么不可变特征的实现可以是可变的?

哪些特征通过 `Deref` 而哪些不通过?

特征中定义的类型与一般定义的类型之间的区别

在 Rust 中,为什么整数溢出有时会导致编译错误或运行时错误?

Rust 中函数的类型同义词

为什么这里需要类型注解?

Rust:为什么在 struct 中borrow 引用会borrow 整个 struct?