Reducing Raw Pointer Footguns: Preventing Reference Aliasing Violations at Compile Time
Rust Internals [Unofficial]
May 18, 2026
Thank you, I just realized that. I explored some ways to prevent the pointer from being returned, ran into difficulties because of the current limitations in the stable channel, then eventually found the best way :]
- The reference case has no problem when I was in the process of creating the new code, I just added a lifetime to the reference in the closure
Now the pointer :
- I tried to implement a trait for detection, but the orphan rule prevents this solution. A trait based solution in stable is only possible by manually implementing the trait for all non pointer types and pointer types
- The trait based solution becomes nicer in the unstable nightly channel with the
auto_traitsandnegative_implsfeatures. Or thespecializationfeature to override the trait implementation - However, all trait based solutions still allow an escape via wrapping the raw pointer inside a custom struct. This requires manually implementing the detection trait for the struct, eg via a manually implement the trait or macro syntax sugar that wraps the impl trait. At least now it explicitly makes one aware that it can be dangerous, but not ergonomic because it requires manual ritual
- A proc macro based solution is only aware of raw tokens, not types. It checks if the type returned in the closure is a raw pointer. If the raw pointer is wrapped inside a struct, then adding
#[derive(Guard)]to the struct allows the proc macro to check if there is a raw pointer inside. But it can still escape if forgot to use the derive guard - The best approach that I found is using the compile time reflection feature available in nightly. This one guarantees detection of the raw pointer and can not be tricked
I have updated the opening post with the latest code that uses compile time reflection :]
Now we can not escape the pointer ouside the clossure:
let ptr = guard.with_mutable_pointer(|ptr| ptr);
guard.with_mutable_reference(|r| {
});
It will cause compile time error:
Discussion in the ATmosphere