gpt4 book ai didi

rust - 为什么我不能调用具有临时值的方法?

转载 作者:行者123 更新时间:2023-11-29 08:10:27 28 4
gpt4 key购买 nike

我不能在下面的代码中调用 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

如果我先绑定(bind)Foo::new(words) 的值,然后调用split_first 方法就没有问题。

这两种调用方法在直觉上应该是相同的,但又有些不同。

最佳答案

简答:删除 split_firstself 参数的 'a 生命周期:fn split_first(&self) -> &'a str ( playground ).

长答案:

当你写这段代码时:

struct Foo<'a> {
part: &'a str,
}

impl<'a> Foo<'a> {
fn new(s: &'a str) -> Self {
Foo { part: s }
}
}

您告诉编译器所有 Foo 实例都与某个生命周期 'a 相关,该生命周期必须等于或短于作为参数传递给的字符串的生命周期Foo::new。该生命周期 'a 可能 不同于每个 Foo 实例的生命周期。然后当你写:

let words = "Sometimes think, the greatest sorrow than older";
Foo::new(words)

编译器推断'a 的生命周期必须等于或小于words 的生命周期。除非有任何其他约束,编译器将使用 words 的生命周期,它是 'static,因此它在程序的整个生命周期内都是有效的。

当您添加 split_first 的定义时:

fn split_first(&'a self) -> &'a str

您正在添加一个额外的约束:您是说 'a 也必须等于或短于 self 的生命周期。因此,编译器将采用 words 的生命周期和临时 Foo 实例的生命周期中较短的一个,这是临时的生命周期。 @AndersKaseorg's answer解释为什么这不起作用。

通过删除 self 参数上的 'a 生命周期,我将 'a 从临时生命周期中去除,因此编译器可以再次推断出 'awords 的生命周期,该生命周期足以让程序运行。

关于rust - 为什么我不能调用具有临时值的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54229893/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com