pretzelhammer / rust-blog

Educational blog posts for Rust beginners
Apache License 2.0
7.57k stars 400 forks source link

Struct methods can also NOT have elided lifetimes right? #62

Closed davidatsurge closed 2 months ago

davidatsurge commented 2 years ago

The list of common misconceptions contains:

if you've ever written a struct method ... then your code has generic elided lifetime annotations all over it.

But that's not always true right?

struct A {}
impl A {
    fn method(self) -> A {
        self
    }
}
pub fn main() {
    let a = A {};
    a.method();

}
pretzelhammer commented 2 months ago

yeah, you're right.

be careful about making assumptions about methods which take/return self tho, because self could contain refs, and those refs lifetimes would be elided, e.g.

struct Struct<'a> {
    s: &'a str,
}

impl Struct<'_> {
    // looks pretty innocent, no lifetimes or references in sight
    fn method(self) -> Self {
        self
    }
}

desugars to:

struct Struct<'a> {
    s: &'a str,
}

impl<'a> Struct<'a> {
    fn method(self: Struct<'a>) -> Struct<'a> {
        self
    }
}

but anyway, i updated the wording in the article in this commit, thanks for making this issue