我无法在以下代码中调用
编译器会给我一个错误消息。
如果我先绑定
这两种调用方法本应该是直观上相同的,但实际上有所不同。
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
方法是没有问题的。这两种调用方法本应该是直观上相同的,但实际上有所不同。