How to perform nested casts

Generally it is possible to use comptime code and type reflection to create the type you need.

  • const T = @TypeOf(anytype_parameter) gets you the type of the parameter
  • @typeInfo(T) returns std.builtin.Type which describes the details of what kind of type T actually is
  • then you can for example switch on that type-information and make decisions on what to do with it (create a @compileError, compute some other type that should be used as casting result etc.)

All that said be careful with @constCast it is relatively rarely needed in practice and it only works if the memory is either not actually mutated, or is guaranteed to be actually mutable memory (e.g. literals are most likely in read-only memory and trying to mutate them would cause a segfault).

Usually it is better to either consistently work with const pointers or non-const pointers. (However sometimes some (usually C) code forces you to use const cast)


I think without a more concrete code example it is difficult to answer more than:
Yes declaring the type on the const/variable is the intended way and you may have to write comptime code to compute the type via comptime/meta-programming/reflection.

So something like this is in the realm of normal expectation:

fn ResultType(comptime T: type) type {
    return ...; // map T to some other type, e.g. by switching on the @typeInfo
}

...
    const result: ResultType(@TypeOf(anytype_parameter)) = @ptrCast(anytype_parameter);
1 Like