てけもぐ Tech 忘備録

rust の &raw と as *const/*mut

対象

rust 初学者

内容

rust で、&raw が必要な理由を調べても、大元の記事が見つかりにくかったのでメモしておきます。

これですかね。Rust standard library - macro addr_of このマクロは &raw と機能としては同じ。

Creates a const raw pointer to a place, without creating an intermediate reference.

なぜ as *const T とか、 as * mut T でキャストしただけじゃだめな時があるかと言うと、creating an intermediate reference になってしまうから。下の方にも書いてありますね。

However, &expr as *const _ creates a reference before casting it to a raw pointer, and that reference is subject to the same rules as all other references. This macro can create a raw pointer without creating a reference first.