TypeScript-style untagged unions don't exist in (safe) Rust. Instead, "or" is done with enums (which are tagged/discriminated unions—https://en.wikipedia.org/wiki/Tagged_union). One difference is that in TypeScript `number | number` reduces to just `number`, but Rust enums don't work that way (`enum Foo { A(f64), B(f64) }` has two distinct variants).
struct Wrapper<T> {
value: T,
}
trait Boolable {
fn to_bool(self) -> bool;
}
impl Boolable for bool {
fn to_bool(self) -> bool {
self
}
}
impl Boolable for f64 {
fn to_bool(self) -> bool {
self != 0.0
}
}
fn to_bool(x: Wrapper<impl Boolable>) -> bool {
x.value.to_bool()
}
fn unwrap<T>(x: Wrapper<T>) -> T {
x.value
}
fn main() {
let a = Wrapper { value: 1.23 };
let b = Wrapper { value: true };
to_bool(a);
to_bool(b);
let c = Wrapper { value: "whatever" };
unwrap(c);
}
I find there's a decent mental shift switching between TypeScript and Rust, despite some superficial similarities. I use both languages in different codebases and it usually takes me a bit to adjust when hopping back and forth. Both type systems have useful worldviews, but they're pretty different, and they nudge you towards different ways of structuring your code.
Check out these equivalent-ish programs:
TypeScript: https://www.typescriptlang.org/play?#code/C4TwDgpgBA6gTgQzJO...
Rust: https://play.rust-lang.org/?version=stable&edition=2018&gist... In Rust you also have traits to play with: https://play.rust-lang.org/?version=stable&edition=2018&gist... I find there's a decent mental shift switching between TypeScript and Rust, despite some superficial similarities. I use both languages in different codebases and it usually takes me a bit to adjust when hopping back and forth. Both type systems have useful worldviews, but they're pretty different, and they nudge you towards different ways of structuring your code.