【发布时间】:2019-01-17 06:04:17
【问题描述】:
我无法在下面的代码中调用Foo::new(words).split_first()
fn main() {
let words = "Sometimes think, the greatest sorrow than older";
/*
let foo = Foo::new(words);
let first = foo.split_first();
*/
let first = Foo::new(words).split_first();
println!("{}", first);
}
struct Foo<'a> {
part: &'a str,
}
impl<'a> Foo<'a> {
fn split_first(&'a self) -> &'a str {
self.part.split(',').next().expect("Could not find a ','")
}
fn new(s: &'a str) -> Self {
Foo { part: s }
}
}
编译器会给我一个错误信息
error[E0716]: temporary value dropped while borrowed
--> src/main.rs:8:17
|
8 | let first = Foo::new(words).split_first();
| ^^^^^^^^^^^^^^^ - temporary value is freed at the end of this statement
| |
| creates a temporary which is freed while still in use
9 |
10 | println!("{}", first);
| ----- borrow later used here
|
= note: consider using a `let` binding to create a longer lived value
如果我先绑定Foo::new(words)的值,然后调用split_first方法就没有问题了。
这两种调用方法在直觉上应该是相同的,但在某种程度上是不同的。
【问题讨论】:
-
编译器会直接告诉您问题所在:
temporary value is freed at the end of this statement、creates a temporary which is freed while still in use和borrow later used here。我认为错误信息很清楚。如果没有,请告诉我们您的理解是什么。 -
我不认为重复适用,因为如果没有被错误的显式生命周期阻止,临时 可以毫无问题地删除。