Skip to content

Add accessor by reference to immutable #198

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

Closed
wants to merge 1 commit into from
Closed

Add accessor by reference to immutable #198

wants to merge 1 commit into from

Conversation

carlomilanesi
Copy link

Currently, if I have:

#[nutype(validate(not_empty), derive(Debug, PartialEq, Clone))]
pub struct Username(String);

let u = Username::try_new("Jack").unwrap();
assert_eq!(u.into_inner(), "Jack");
assert_eq!(u.into_inner(), "Jack");

At the last line I get the error:

use of moved value: `u`

Instead, with my change, I can write:

let u = Username::try_new("Jack").unwrap();
assert_eq!(u.inner(), "Jack");
assert_eq!(u.inner(), "Jack");

@greyblake
Copy link
Owner

greyblake commented Jan 4, 2025

@carlomilanesi Hi!
Thanks for your effort, though I have to decline your contribution.
For your case you should derive AsRef and use it:

use nutype::nutype;

#[nutype(
    validate(not_empty),
    derive(Debug, PartialEq, Clone, AsRef)
)]
pub struct Username(String);

fn main() {
    let u = Username::try_new("Jack").unwrap();
    assert_eq!(u.as_ref(), "Jack");
    assert_eq!(u.as_ref(), "Jack");
}

I hope that helps!

@greyblake greyblake closed this Jan 4, 2025
@carlomilanesi
Copy link
Author

Ok, but I think you should explain better in documentation the uses of into_inner and of as_ref to access the value.

@greyblake greyblake mentioned this pull request Jan 4, 2025
@greyblake
Copy link
Owner

@carlomilanesi Thanks for you feedback!
I've updated the docs #200

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

Successfully merging this pull request may close these issues.

2 participants