#obtaining type of elements of unallocated slice ... any danger of this?

1 messages · Page 1 of 1 (latest)

cinder glacier
#

Been experimenting with delayed and grouped allocations of multiple slices, and came upon a question I hadn't considered before. Suppose an unallocated slice is made:

var a: []i32 = undefined;

we can obtain the type of "a" using @TypeOf(a), which returns "[]i32" but how can we obtain the type of the elements of this slice?

Just realized that one could use:

@TypeOf(a[0])

or even

@TypeOf(a[9999])

both return "i32" even though nothing has been allocated.

So, is there any danger to using this? Is there a better way?

rustic geyser
#

a better way is typeInfo

#

type_info.Pointer.Child iirc

#

@typeInfo(@TypeOf(a)).Pointer.Child

cinder glacier
prime orbit
#

cleaner still is std.meta.Child, which just wraps that: std.meta.Child(@TypeOf(a))
also, while this is a better approach, it's worth pointing out that your original idea is still completely safe. from the docs (https://ziglang.org/documentation/master/#TypeOf):

The expressions are evaluated, however they are guaranteed to have no *runtime* side-effects.

so effectively, the runtime-known value is irrelevant, it's only the type that matters

cinder glacier
#

(the @TypeOf(a[0]) is my early experimentation felt dangerously hackish.)