greyblake / nutype

Rust newtype with guarantees 🇺🇦 🦀

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Considering `try_` prefix for creating nutype objects

DK26 opened this issue · comments

Hello! =)

Thanks your awesome work on nutype, it has been very helpful!

I was thinking, since the new() method can fail, this could be better described by adding a try_ prefix (e.g. try_new()).

Since Rust already has the TryFrom trait (had a little trouble implementing it myself), I'd like to suggest that to be the de-facto way to create nutypes objects.

What do you think?

Hi, thank you for your appreciation of crate.
I want to apologize for the silence, I was on vacation.

The idea to use new for all was taken from bounded_inter.

The fact that ::new() may return an error is already reflected in the signature, so I don't think it's a really a problem.

I am not sure, maybe you miss this: if there is no validation, ::new() is not fallible, so it returns exactly a newtype (not Result)

Since Rust already has the TryFrom trait (had a little trouble implementing it myself)

You can derive TryFrom with nutype:

#[nutype(
    sanitize(trim, lowercase)
    validate(not_empty, char_len_max = 20)
)]
#[derive(TryFrom)]
pub struct Username(String);

Or if you'll use 0.4.0-beta.2:

#[nutype(
    sanitize(trim, lowercase),
    validate(not_empty, char_len_max = 20),
    derive(TryFrom),
)]
pub struct Username(String);

(the new 0.4.0 version is going to be released soon).

For now I am going to close the issue, but I am fine to answer your further questions or reconsider my decision if you put more arguments.

Thank you!

Consider fallible new is typically bad practice, I'm thinking that if a type has validation, no ::new() should be generated, and possibly the TryFrom trait should be auto-implemented. This was what I expected coming into the library and was surprised that the signature of ::new() changed between my nutypes that did and didn't have validation.

For a reference.
Standard library is using try_new for fallible constructors: https://doc.rust-lang.org/std/?search=try_new (not stabilized yet).

If the change will be made, it should used diagnostic to help end users to navigate through the error message.

We should also considering introducing try_new and using deprecation mechanism for new (with validation).