Best practice for fallible constructor, clippy::new_ret_no_self

i'm just trying out clippy for the first time, ran it on some code of mine and it made some helpful suggestions that were easy to change :slight_smile:
However, i get

warning: methods called `new` usually return `Self`

at one point where i have a method SomeType::new(a : SomeParameter, b : SomeParameter) -> Result<Self,Error>, where a and b are user inputs into my application, and not every combination of them is valid for constructing a SomeType instance. Is there an established naming convention for constructors that may fail?

Thanks! :slight_smile:

1 Like

You can name it something like from_config, from_params, with_config, with_params, etc. That is, with_ and from_ are commonly used prefixes for constructors that arenโ€™t, essentially, the default one (which is what new usually refers to). But thatโ€™s more about taking some arguments rather than being fallible or not.

That said, Iโ€™m not sure I agree with this clippy lint and well known crates have many "violations" - eg tokio has plenty of new() that are fallible. So if you canโ€™t come up with an obviously better name, just ignore this lint in that place.


Ok, thanks for the alternate name suggestions, i'll keep them in mind in the future. For this specific instance, i've decided to stick with new and put #[allow(clippy::new_ret_no_self)] above it to disable the lint, because it's really the only sensible way to construct that type.

Thanks :slight_smile:

1 Like

You could also open a clippy issue asking for the lint to allow Option<Self>, Result<Self, _>, impl Future<Output = Self>, etc.

1 Like

Haha, i looked in their bugtracker, and it seems this was fixed in their git just three days ago if i understand that thread correctly :smiley:

1 Like