Best way to cast a fixed array?

a := [4]u32{1, 1, 1, 1}
b := [4]f64(a) // This doesn't work
c := [4]f64{f64(a.x), f64(a.y), f64(a.z), f64(a.w)} // This does

This can be tedious for larger arrays. Should I just iterate over the array and cast individually into a separate array? That’s what I’ve been doing and it’s not a problem. I’m just curious what the alternatives are.

This is not a cast. This is data transformation.

[4]u32 and [f]f64 do not have the same size, and the bit patterns for ints and floats is not the same.

Stepping back, it’s better to structure your code such that transformations like this are not needed. Use the same type throughout.

If you need it, just iterate and convert each element.

Odin’s own documentation uses int to float conversion as the first example of a cast. Data transformation is called casting.

1 Like

You can use a function like this:

// Casts array A to type T
acast :: proc(array: [$L]$A, $T: typeid) -> [L]T {
    res := [L]T {}
    #no_bounds_check for i in 0..<L {
        res[i] = cast(T) array[i]
    }
    return res
}

main :: proc() {
    a := [4]u32 { 5, 33, 2, 6}
    b := acast(a, f32)
}

I feel like this is already in a Core package somewhere…

1 Like

core:math/linalg has an array_cast proc for this, and also some similar procs for specific target types (e.g. to_f32). This is effectively the same thing as acast above.

2 Likes