首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Self和struct名称之间有什么不同会产生这个错误?

Self和struct名称之间有什么不同会产生这个错误?
EN

Stack Overflow用户
提问于 2022-11-08 01:46:32
回答 1查看 33关注 0票数 0

此代码运行良好:

代码语言:javascript
复制
#[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:

代码语言:javascript
复制
fn bar_func(arg1: &str) {
    let f = Self { data : arg1.split_whitespace().collect() };
    println!("{:?}", f.data);
}

我得到了一个终生的错误:

代码语言:javascript
复制
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,所以你可以想象,这让我陷入了很长一段时间,而幸运的是,当我试图在一个最小的例子中隔离这个问题时,我发现它与结构名称很好地工作。

这两者是否等同,若然,两者有何分别?

EN

回答 1

Stack Overflow用户

发布于 2022-11-08 01:52:27

他们不一样。

FooFoo<'_>,具有推断(或省略)生存期,这意味着我们可以使用arg1的生存期。

但是,Self保留当前类型的泛型参数,其中包括生存期。因此,FooSelf的生存期指的是impl Foo<'_>中的被省略的'_,这是一个与arg1的生存期不兼容的独特的泛型生存期。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74354849

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档