Struct rust_examples::typing::Positive [−][src]
pub struct Positive(_);Expand description
Opaque wrapper around f64 which adds static semantics that the float has positive value.
The benefit of such abstraction is two fold:
- It adds static information about legal values that the compiler can’t possibly know about
- while it incurs zero cost at runtime (it gets “compiled away” and behaves as an ordinary f64)
While it might seem annoying to work with Positive instead of plain f64, one can derive
many traits implemented for f64 so that instances of Positive can be a drop-in replacement
for it in many cases.
Additionally, there is an incentive in the Rust team to further mitigate the pain to work with
these wrappers by introducing something like a #[newtype_derive] macro inspired by the
newtype pattern from Haskell.
Note this could be generalized with the num crate:
use num::Float;
struct Positive<F: Float>(F);Implementations
This forces clients to always check if it’s ok. One cannot initialize a tuple struct which contains private fields.
So the following code does not compile because f64 is a private field in Positive.
use rust_examples::typing::Positive;
let _ = Positive(-24.);The only option is then to use this factory method and therefore check the result.
use rust_examples::typing::Positive;
assert_eq!(Positive::new(-24.), None)Note that this is not OOP, one can call Positive::as_u32 as an ordinary function:
use rust_examples::typing::Positive;
let pos = Positive::new(42.).expect("positive number");
let int = unsafe { Positive::as_u32(&pos) };
assert_eq!(int, 42);Safety
The safety is guaranteed by the construction of Positive instances via Positive::new.
Trait Implementations
This method returns an ordering between self and other values if one exists. Read more
This method tests less than (for self and other) and is used by the < operator. Read more
This method tests less than or equal to (for self and other) and is used by the <=
operator. Read more
This method tests greater than (for self and other) and is used by the > operator. Read more
Auto Trait Implementations
impl RefUnwindSafe for Positive
impl UnwindSafe for Positive
Blanket Implementations
Mutably borrows from an owned value. Read more
