Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Considering try_ prefix for creating nutype objects #91

Open
DK26 opened this issue Sep 6, 2023 · 2 comments
Open

Considering try_ prefix for creating nutype objects #91

DK26 opened this issue Sep 6, 2023 · 2 comments

Comments

@DK26
Copy link

DK26 commented Sep 6, 2023

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?

@greyblake
Copy link
Owner

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!

@asasine
Copy link

asasine commented Feb 22, 2024

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.

@greyblake greyblake reopened this Feb 23, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants