Array Initialization "Shortcut"

I found the following feature by accident. In one of my program I converted a one dimensional array to a two dimensional one and forgot to add the second dimension in one place. Surprisingly (to me) the compiler didn’t flag it.

I was in the process of creating a short program to report the problem when I realized it seems to be a feature. You can initialize an entire array or an entire array dimension by assigning it a single value. I checked the overview and Understanding the Odin Programming Language but couldn’t find a reference to that type of initialization.

xs: [2][10]int
xs[0] = 10
xs[1] = 20
fmt.printf(“xs: %d, %d, %d\n”, xs[0][9], xs[1][0], xs[1][9])

==> xs: 10, 20, 20

ys: [10]int
ys = 5
fmt.printf(“ys: %d, %d\n”, ys[0], ys[9])

==> ys: 5, 5

I am just curious if this is described anywhere.

Thanks

1 Like

It’s called Array Programming and it’s mentioned in the overview but that specific example is not given. It uses SIMD under the hood so it should be faster. Although, if you had used a loop, an optimized build might vectorize that loop anyway.

1 Like

I had read about the Array Programming features of Odin. I just didn’t realize it extended to initialization. I was surprised at first but I like it.

It’s more of a consequence of the rules.

x := [3]f32{1, 2, 3}
y := x * 5.8 // this 5.8  gets "converted" to `[3]f32`