Skip to content

Instantly share code, notes, and snippets.

@amachang
Last active June 28, 2023 12:48
Show Gist options
  • Select an option

  • Save amachang/a34d513fe3ad8f5f78e91c79b1eedf39 to your computer and use it in GitHub Desktop.

Select an option

Save amachang/a34d513fe3ad8f5f78e91c79b1eedf39 to your computer and use it in GitHub Desktop.
[Rust] &'static な参照になれる値

&'static な参照になれる値

struct Foo { }

fn bar() {
  let ref: &'static _ = &Foo { };
}

みたいに特定の値は &'static で参照できる。これを rvalue static promotion という。

これは Foo が明らかに定数で、その不変な参照しかないので、グローバルな const 変数として扱えるからである。

コンパイル時に値が定数に確定していることがわかるので、コンパイラは &'static として参照することを許す

実際はバイナリファイルにその構造体のメモリ表現が埋め込まれていて、その番地を見てるだけって感じ。

以下のように関数の返り値だと例え定数でも &'static にで参照できない

struct Foo { }

impl Foo { fn const new() -> Self { Self { } } }

fn bar() {
  let ref: &'static _ = &Foo::new();
}

ただ、 rust の標準ライブラリには以下のように関数の返り値でも &'static を許すようなものもある。

例えば、 RawWakerVTable とか

fn foo() {
  let v: &'static _ = &RawWakerVTable::new(...);
}

これは RawWakerVTable の new に #[rustc_promotable] というディレクティブがついていて特別扱いされているからである。

ちなみに、このディレクティブは rust の標準ライブラリでしか使えない。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment