What's the difference between Self vs type name for method return?

What's the difference between Self vs type name for return type?

Being more specifically, I can compile following variations and looks the same. Is there any difference?

struct Foo {
  foo: u8,
}

impl Foo {
  fn new1() -> Self {
    Self { foo: 1}
  } 
  fn new2() -> Foo {
    Foo { foo: 1}
  } 
  fn new3() -> Self {
    Foo{ foo: 1}
  } 
}

No difference, Self is just syntactic sugar inside trait and impl blocks and type definitions to refer to the implementing type.

3 Likes

Self is more helpful for complex generic types.

For example, this is probably wrong:

impl<'a> Bar<'a> {
    fn new<'b>(x: &'b str) -> Bar<'b> { … }
}

since it should instead be

impl<'a> Bar<'a> {
    fn new(x: &'a str) -> Bar<'a> { … }
}

and the easiest way to not make that mistake is to write it as -> Self instead.

8 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.