tl;dr in Rust, is there a "strong" type alias (or typing mechanism) such that the rustc
compiler will reject (emit an error) for mix-ups that may be the same underlying type?
Problem
Currently, type aliases of the same underlying type may be defined
type WidgetCounter = usize;
type FoobarTally = usize;
However, the compiler will not reject (emit an error or a warning) if I mistakenly mix up instances of the two type aliases.
fn tally_the_foos(tally: FoobarTally) -> FoobarTally {
// ...
tally
}
fn main() {
let wc: WidgetCounter = 33;
let ft: FoobarTally = 1;
// whoops, passed the wrong variable!
let tally_total = tally_the_foos(wc);
}
Possible Solutions?
I'm hoping for something like an additional keyword strong
strong type WidgetCounter = usize;
strong type FoobarTally = usize;
such that the previous code, when compiled, would cause a compiler error:
error[E4444]: mismatched strong alias type WidgetCounter,
expected a FoobarTally
Or maybe there is a clever trick with struct
s that would achieve this?
Or a cargo module that defines a macro to accomplish this?
I know I could "hack" this by type aliasing different number types, i.e. i32
, then u32
, then i64
, etc. But that's an ugly hack for many reasons.
Is there a way to have the compiler help me avoid these custom type alias mixups?