meilisearch/meilisearch-rust

Using Self rather than writing the Struct name

Closed this issue · 4 comments

Currently, for every Struct initialization, the name of the struct is used as the return type.
Rust supports Self, which denotes the Struct itself (https://doc.rust-lang.org/reference/paths.html#self-1)

Example:

In src/client.rs

pub fn new(host: impl Into<String>, api_key: impl Into<String>) -> Client {
        Client {
            host: host.into(),
            api_key: api_key.into(),
        }
    }

Replacing the snippet using Self

pub fn new(host: impl Into<String>, api_key: impl Into<String>) -> Self {
        Self {
            host: host.into(),
            api_key: api_key.into(),
        }
    }

Rather than writing Client as a return type, it can be replaced with Self which denotes the Client struct itself, and same for the Client struct initialization.

Benefits:

  • flexibility: If you decide to change the name of your type, it's one less place to update.
  • conciseness: Self is shorter than MyType or SomeOtherType and especially ThisTypeWithGenerics<'a, 'b, A, String>.

PS: I would be glad to work on this issue

Hey @VoidCupboard ! This seems to be a very nice addition. I'm not aware of this best practice (as you can see) so let me come back to you as I'm going to ask the opinion of one of the rust engineers of Meilisearch.

No problem @bidoubiwa 😄

Hey I checked with @Kerollmops and @irevoire and they prefer not as, if the struct starts to grow it will become harder and harder to know in which structure implementation we currently are when working on it.

And for only adding it to the initializer, we would lose consistency with the implementations still using the name of the struct. If we do only add it in the initializer, we would still have to change the name of the struct in every implementation.

Oh okay, that makes sense! I will close the issue then :)