-
Notifications
You must be signed in to change notification settings - Fork 560
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
Implement TryInto
for Value
#947
base: master
Are you sure you want to change the base?
Conversation
This comment was marked as spam.
This comment was marked as spam.
TryInto shouldn't be implemented explicitly, you should implement TryFrom instead. See https://doc.rust-lang.org/std/convert/trait.TryInto.html#implementing-tryinto Also, TryInto/TryFrom in general is the wrong choice here. Similarly to From/Into, TryFrom/TryInto should be used to convert between types that are semantically equivalent, but differ only in programmatical representation. For example, std implements TryFrom to convert integer<->integer and list<->list. Instead, there should be |
I don’t see why you can’t just use Edit: Nevermind, I misread. Even so, it does feel like the kind of thing that should be done strongly-typed to begin with. |
Strong typing is definitely preferred all-else-equal, but in this particular case it really does make more sense to keep it loosely typed until later in the program. For my use-case, we don't have enough information up-front to know what the shape of the data should be. Once we know what the shape should be, then we use more well-defined types. |
FWIW, using u64 as an example, we already have Value implementing TryFrom, which breaks this principle. I think it's only fair to stay consistent. (Which is to either add TryInto or remove TryFrom). |
Fixes #902
This PR implements
TryInto
for convertingValue
into common types such asString
,str
,u64
,f64
,i64
,()
,Vec
andMap
. I've implemented these both for ownedValue
and borrowedValue
.Justification and Use Case
I know there's been some skepticism from the maintainer about the need for
TryInto
impls when one can use the full deserialization machinery to retrieve a concrete typed value from aValue
, but I'd like to justify this PR by pointing to both the ergonomics of havingTryInto
and the efficiency ofTryInto
over full deserialization (especially when borrowing).For my use-case, I have a struct that delays fully deserializing all values until much later in the program.
Much deeper in the code, inputs get wrapped into a container like so:
All of this machinery provides a really nice interface to calling code, that can simply call into
Inputs
like so:And importantly, because inputs can be quite large, everything is done via borrows, avoiding unnecessary cloning and allocations.
This is my specific use-case, but I'm sure there are other use-cases where having reasonable and straightforward
TryInto
impls for Value would be ergonomic and timesaving.Thank you.