{
  "$type": "site.standard.document",
  "bskyPostRef": {
    "cid": "bafyreifyak5v5yfgteeo5ok67lb3mh4yv77mf4v2eobdgb2caaydc3khfe",
    "uri": "at://did:plc:ivbknywyskln22er3nkssdhl/app.bsky.feed.post/3mlzidg4thde2"
  },
  "path": "/t/reducing-raw-pointer-footguns-preventing-reference-aliasing-violations-at-compile-time/24301?page=2#post_25",
  "publishedAt": "2026-05-17T03:29:14.000Z",
  "site": "https://internals.rust-lang.org",
  "textContent": "I just added the `#[guard]` attribute and the `guard_block!({ ... })` macro to improve the guard\n\nPreviously, the guard did not cover this. Now, it covers this:\n\n\n    #[guard]\n    fn a(guard: &AliasingGuardMut<Vec<i32>>) {\n        let direct_ptr = guard.as_ptr();\n        let mutable_reference = guard.mutable_reference();\n        unsafe { *direct_ptr = vec![1] };\n        *mutable_reference = vec![1];\n    }\n\n    fn main() {\n\n        let mut s = vec![1, 2, 3];\n\n        let mut guard = AliasingGuardMut::from_reference(&mut s);\n\n        guard_block!({\n            let b = &raw mut s;\n            let a = guard.mutable_reference();\n            unsafe { *b = vec![1] };\n            *a = vec![1];\n        });\n\n    }\n\n\nIt produces the following compile time error:\n\nThere is still case that can not be covered yet, it is when the declaration is ouside the guard. This is because, during macro expansion, we do not know whether the dereferenced variable is a pointer or a reference. Once compile time reflection is available, we will be able to determine the variable’s type at compile time and cover this case as well\n\n\n    fn main() {\n\n        let mut s = vec![1, 2, 3];\n\n        let mut guard = AliasingGuardMut::from_reference(&mut s);\n        let b = &raw mut s;\n\n        guard_block!({\n            let a = guard.mutable_reference();\n            unsafe { *b = vec![1] };\n            *a = vec![1];\n        });\n\n    }\n",
  "title": "Reducing Raw Pointer Footguns: Preventing Reference Aliasing Violations at Compile Time"
}