How to perform nested casts

I am trying to do @constCast(@ptrCast(...) but get error that @ptrCast needs to know the result type. The same happens when I try most other casts nested. I can workaround it with @as but I am myself not always know what I would need to write there because it can be dynamic from anytype… So how it is recommended 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

Thank you for detailed answer and especially for showing me trick with writing code inside type definition of variable. I knew I can write arbitrary code (like if statement) in the return type of function but didn’t expect it is possible here.

Btw. I wanted to show example but I somehow can’t reproduce it now at all… The only thing I can surely say it was involving C pointers but again I can’t reproduce it now because it started to compile for some reason :sweat_smile:

1 Like