Casting
In Odin, there are numerous types of casts:
cast
Basic casttransmute
Convert the bits of one type to another of the same sizeunion_cast
Convert from a union type to its variant
main :: proc() {
// `cast`
x: i32 = 123;
y: i64 = cast(i64)x;
// Named types are distinct from their base type
Seconds :: i64;
elapsed_time := 2 * Seconds;
raw_number: i64 = cast(i64)elapsed_time;
// TODO: Try removing the above cast and see what happens
// `transmute`
// See: https://en.wikipedia.org/wiki/Fast_inverse_square_root
Q_rsqrt :: proc(number: f32) -> f32 {
threehalfs :: 1.5;
x2: f32 = number * 0.5;
y: f32 = number;
i: i32 = transmute(i32)y; // evil floating point bit level hacking
i = 0x5f3759df - ( i >> 1 ); // what the fuck?
y = transmute(f32)i;
y = y * ( threehalfs - ( x2 * y * y ) ); // 1st iteration
// y = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration, this can be removed
return y;
}
// `union_cast`
Entity :: union {
// Common fields
id: u64,
position: [vector 3]f32,
orientation: quaternion128,
name: string,
// Variants
Frog{
jump_height: f32,
ribbit_volume: f32,
},
Door{
openness: f32,
},
Monster{
speed: f32,
scary_factor: int,
},
}
e: Entity = Entity.Frog{id = 123, name = "Frank", jump_height = 2.2};
// Value and `ok` if valid
f1, ok := union_cast(Entity.Frog)e;
// Ignore the check
f2, _ := union_cast(Entity.Frog)e;
// Panics if the cast is not possible
f3 := union_cast(Entity.Frog)e;
}