- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我写了下面的代码来从 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/
我正在开发一个使用多个 turtle 的滚动游戏。玩家 turtle 根据按键命令在 Y 轴上移动。当危害和好处在 X 轴上移动时,然后循环并改变 Y 轴位置。我尝试定义一个名为 colliding(
我不明白为什么他们不接受这个作为解决方案,他们说这是一个错误的答案:- #include int main(void) { int val=0; printf("Input:- \n
我正在使用基于表单的身份验证。 我有一个注销链接,如下所示: 以及对应的注销方法: public String logout() { FacesContext.getCurren
在 IIS7 应用程序池中有一个设置 Idle-time out 默认是 20 分钟,其中说: Amount of time(in minutes) a worker process will rem
我是一名优秀的程序员,十分优秀!