此代码运行良好:
#[derive(Debug)]
struct Foo<'a> {
data: Vec<&'a str>,
}
impl Foo<'_> {
fn bar_func(arg1: &str) {
let f = Foo { data : arg1.split_whitespace().collect() };
println!("{:?}", f.data);
}
}
fn main() {
Foo::bar_func(&"hey split me!");
}但是,如果我在创建结构时更改Foo for Self:
fn bar_func(arg1: &str) {
let f = Self { data : arg1.split_whitespace().collect() };
println!("{:?}", f.data);
}我得到了一个终生的错误:
error: lifetime may not live long enough
--> src/main.rs:9:31
|
6 | impl Foo<'_> {
| -- lifetime `'2` appears in the `impl`'s self type
7 |
8 | fn bar_func(arg1: &str) {
| - let's call the lifetime of this reference `'1`
9 | let f = Self { data : arg1.split_whitespace().collect() };
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ argument requires that `'1` must outlive `'2`
|
= note: requirement occurs because of the type `SplitWhitespace<'_>`, which makes the generic argument `'_` invariant
= note: the struct `SplitWhitespace<'a>` is invariant over the parameter `'a`
= help: see <https://doc.rust-lang.org/nomicon/subtyping.html> for more information about variance直到现在,我还以为它们是可以互换的,而且我大部分时间都会使用Self,所以你可以想象,这让我陷入了很长一段时间,而幸运的是,当我试图在一个最小的例子中隔离这个问题时,我发现它与结构名称很好地工作。
这两者是否等同,若然,两者有何分别?
发布于 2022-11-08 01:52:27
他们不一样。
Foo是Foo<'_>,具有推断(或省略)生存期,这意味着我们可以使用arg1的生存期。
但是,Self保留当前类型的泛型参数,其中包括生存期。因此,Foo与Self的生存期指的是impl Foo<'_>中的被省略的'_,这是一个与arg1的生存期不兼容的独特的泛型生存期。
https://stackoverflow.com/questions/74354849
复制相似问题