Array of const elements

When I try to define an array const a: [2]const i32 = [_]const i32{1,2}; I get an error similar to expected type got const.

I know that writing const a: [2]i32 = [_]i32{1,2}; solves the problem but what to understand the semantic meaning of const. It doesn’t seem to be only for variables because []const u8 is a valid type. So I guess it is for variables, variables of type type, pointers and function pointers. Is my conclusion correct?

1 Like

Yes, const can be used on a variable (to indicate that the variable’s value can’t change) or as a pointer qualifier (to indicate that you can’t change the value pointed to through that pointer).

The key distinction here is that arrays, such as [2]i32, are values rather than pointers, just like other familiar value types such as i64. So just as it wouldn’t make sense to have const i64 as a separate type from i64, it also wouldn’t make sense to have a type [2]const i32. For more information on what it means to apply const to a variable vs as a pointer qualifier, see Converting an "array of slices" to a "slice of slices" - #5 by ianprime0509

5 Likes

const means constant, ‘you can’t change this’.
On a variable, it means the value of the variable is constant, can’t be changed.
As part of a pointer type, it means the value on the other end of the pointer can’t be changed.

You are probably equating [N]T and []T, the first is an array, the latter is a slice which is a pointer type.

1 Like