this post was submitted on 29 Jul 2023
12 points (92.9% liked)
Rust
5965 readers
18 users here now
Welcome to the Rust community! This is a place to discuss about the Rust programming language.
Wormhole
Credits
- The icon is a modified version of the official rust logo (changing the colors to a gradient and black background)
founded 1 year ago
MODERATORS
you are viewing a single comment's thread
view the rest of the comments
view the rest of the comments
The reason I asked the question, was that I wanted to keep an
int
anint
throughout the program.It's not for performance reasons, it's just that I feel like there is a certain elegance in keeping things type safe entirely "for free" much like how
Option<&T>
is actually just a regularT*
, even if it could be pointless in the big picture.Well if you want to keep an int as an int, then use an int. If you want to use Results, use results. Like I said to the other commenter: unless this code is in a very tight loop where performance is crucial, you'll be fine just implementing From/Into to change your Result to and from an int. You're already crossing a language boundary by calling c code from Rust. Is it that much more of an issue to just convert the types when you need to?
Trying to store the results as an int in some magical way just screams premature optimization. You have abstraction tools at your disposal. They may not be zero cost, but they are cheap. Use them.
First and foremost: It's not about optimization, as I have mentioned before. Never once have I intended to optimize the conversion, because I know it is pointless. Stop making that assumption and only then we can continue the discussion.
There is no reason why people cannot use Rust as "C, but actually type-safe". A type-safe representation of C's error code pattern is a part of that. This way the code is "backwards compatible" with debuggers designed for C/C++, such that "-EINVAL" is actually displayed as "-EINVAL" in the debugger and not a mysterious struct of
(discriminant, data)
.Oh I see. I misunderstood the reason for wanting it represented as an int.
I'm wondering if you could just create a wrapper type that only has an int as a member, but then implement a trait on it so that it can act like a result. That, or just pass around your int type in the rust code, and when you need it to act like a result you do a conversion from int to result. Your debugger wouldn't show it as an int at that point, but it wouldn't show any other Result as an int anyway so it would br consistent with other rust code. If this still doesn't work, you could even make a struct that contains both the int and the result and keeps then synchronized. Then, when debugging, you could look into that struct and see the int value like you want.