【发布时间】:2021-12-27 04:30:11
【问题描述】:
当我遇到此错误时,我正在解析文件中的一些字符串输入。通常,如果您将一系列方法链接在一行上或将它们分成多个操作,则应该不会有什么不同。然而在这里,当方法链在一行中时,它不会编译。
拆分成多个语句like so (link to playground)时没有报错
let input = std::fs::read_to_string("tst_input.txt").expect("Failed to read input");
let input = input
.lines()
.map(|l| {
let mut iter = l.split(" | ");
(
iter.next()
.unwrap()
.split_whitespace()
.collect::<Vec<&str>>(),
iter.next()
.unwrap()
.split_whitespace()
.collect::<Vec<&str>>(),
)
})
.collect::<Vec<_>>();
当它在单个语句like so (link to playground) 中时,我得到一个生命周期错误
let input = std::fs::read_to_string("tst_input.txt")
.expect("Failed to read input")
.lines()
.map(|l| {
let mut iter = l.split(" | ");
(
iter.next()
.unwrap()
.split_whitespace()
.collect::<Vec<&str>>(),
iter.next()
.unwrap()
.split_whitespace()
.collect::<Vec<&str>>(),
)
})
.collect::<Vec<_>>()
error[E0716]: temporary value dropped while borrowed
--> src/main.rs:2:17
|
2 | let input = std::fs::read_to_string("tst_input.txt")
| _________________^
3 | | .expect("Failed to read input")
| |_______________________________________^ creates a temporary which is freed while still in use
...
18 | .collect::<Vec<_>>();
| - temporary value is freed at the end of this statement
19 | println!("{:?}", input);
| ----- borrow later used here
|
= note: consider using a `let` binding to create a longer lived value
这两种情况应该实际上相同吗?为什么编译器会以不同的方式对待它们?这可能是编译器错误吗?
【问题讨论】:
标签: function rust compiler-errors compilation method-chaining