I’ll throw in something ala Scott Meyers here that helps clarify the use cases around this. I made a topic about using @constCast
a while ago: Method overloading and deduplication using @constCast - #3 by AndrewCodeDev
I’ve linked to the post with this example:
fn MatchPtrType(comptime Parent: type, comptime Child: type) type {
return if (comptime isConstPtr(Parent)) *const Child else *Child;
}
// @constCast can propgate through optional pointers... ?*const T -> ?*T
pub fn last(self: anytype) ?MatchPtrType(@TypeOf(self), Node) {
if (comptime isConstPtr(@TypeOf(self))) {
return if (self.items.len > 0)
&self.items[self.items.len - 1] else null;
} else {
return @constCast(asConst(@This(), self).last());
}
}
The pattern that works is:
non-const x -> *const x -> @constCast(ptr)
You do not want to go in this direction:
const x -> *const x -> @constCast(ptr)
The reason being is that the compiler has made assumptions about x
because it begins as const. You’re invalidating those assumptions. If you start with non-const, go up to const, and then back down, everything is fine.
- Edit -
I should probably make a Doc on this…