Replies: 1 comment
-
I can of course always write a simple macro that implements /// Implement [`rocket::request::FromParam`] for the given newtype struct.
#[macro_export]
macro_rules! impl_FromParam_newtype {
($Struct:ident($Inner:ty)) => {
impl<'r> rocket::request::FromParam<'r> for $Struct {
type Error = <$Inner as rocket::request::FromParam<'r>>::Error;
fn from_param(param: &'r str) -> std::result::Result<Self, Self::Error> {
<$Inner as rocket::request::FromParam<'r>>::from_param(param).map(Self)
}
}
};
} and it would be used like this: struct BookId(usize);
impl_FromParam_newtype!(BookId(usize)); However, I still think that supporting this feature in rocket itself would be beneficial. |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
I sometimes use newtype structures to represent database identifiers (essentially to avoid mixing them up).
It would be very nice if I could write:
but
#[derive(FromParam)]
only works (as documented) for C-like enums.Would it make sense to also support
#[derive(FromParam)] struct <name>(T);
whereT: FromForm
?Without it, I have to write something like:
(I cannot just use
BookId(id)
because I'd like to keep the constructor private - the struct actually lives in a different module).The main drawback I can see is that I have to repeat
usize
(the inner/raw type) every time I want to useBookId
. If, at some point, I decide thatusize
is not good enough for me and what I really need isuuid::Uuid
, I have to update all HTTP methods that constructBookId
s.It's not a big deal, but I think that implementing automatically
FromParam
for newtype structs would make this kind of pattern more ergonomic and improve developer experience.(P.S.: Sorry for my English, it's not my mother tongue)
(edit: typo)
Beta Was this translation helpful? Give feedback.
All reactions