-
Notifications
You must be signed in to change notification settings - Fork 23
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
Is a generic newtype possible? #130
Comments
Hi @atezet It's not possible at the moment. |
I already like using the library as-is a lot, but definitely looking forward to that! Thanks |
@atezet Btw, if you need only non empty vector, I recommend taking a look at |
Thanks for the suggestion! We tried that at first, and iirc it worked for the cases where we needed a vector, but we also need I also suggested just using Would love to see this to be possible with |
Hey there, I just briefly checked out the interface (no time to check the code), and my example works as expected! I think your observations regarding support for trait bounds and auto derives are very correct. It would be cool if something like (there are better predicates to do this):
would work as well, but that should be covered by #142 |
@atezet Hi, thanks for the feedback! |
@atezet I just finished the work with generics and published |
@atezet So in 0.4.3 it's possible to use generics and to set type bounds. #[nutype(
validate(predicate = |c| c.into_iter().next().is_some()),
)]
struct NonEmpty<C>(C)
where
for<'a> &'a C: IntoIterator; The problem here is that we need to set the As a workaround, it's possible to clone. But of course it's not optimal from the performance perspective: #[nutype(
validate(predicate = |c| c.clone().into_iter().next().is_some())
)]
struct NonEmpty<C: Clone + IntoIterator>(C); |
@atezet I've found a good solution for you. use nutype::nutype;
trait IsEmpty {
fn is_empty(&self) -> bool;
}
impl<T> IsEmpty for T
where
for<'a> &'a T: IntoIterator,
{
fn is_empty(&self) -> bool {
self.into_iter().next().is_none()
}
}
#[nutype(
validate(predicate = |c| !c.is_empty()),
)]
struct NonEmpty<C: IsEmpty>(C);
fn main() {
let number_vector = NonEmpty::try_new(vec![1, 2, 3]).unwrap();
let chars: std::collections::BTreeSet<char> = "abc".chars().collect();
let char_set = NonEmpty::try_new(chars).unwrap();
} |
Hi @greyblake. Sorry for not replying earlier. We're in a final sprint before the code is audited, so I've some quite busy times and will look at using your solution in the next phase. Thanks for putting in the work, I think it looks quite clean already! I really like what |
@atezet No worries! Good luck with the sprint! |
Is it possible to create a generic newtype with
nutype
? When I do, let's say:I get:
The text was updated successfully, but these errors were encountered: