次の例では、クロージャーは必要以上に値を借用します。
fn main () {
let f = |y| { println!("{}", y); };
let x = 4u8;
f(&x);
}
コンパイルエラーの原因:
error: `x` does not live long enough
--> ./test.rs:5:1
|
4 | f(&x);
| - borrow occurs here
5 | }
| ^ `x` dropped here while still borrowed
|
= note: values in a scope are dropped in the opposite order they are created
ただし、引数の型を明示的に宣言すると、期待どおりに機能します。
fn main () {
let f = |y: &u8| { println!("{}", y); };
let x = 4u8;
f(&x);
}
それがバグなのか、予想される動作なのかわからない。 また、ドキュメントでこの効果の説明を見つけることができませんでした。
rustc --version --verbose
:
rustc 1.17.0-nightly (24a70eb59 2017-02-09)
binary: rustc
commit-hash: 24a70eb598a76edb0941f628a87946b40f2a1c83
commit-date: 2017-02-09
host: x86_64-unknown-linux-gnu
release: 1.17.0-nightly
LLVM version: 3.9
検索エンジンの用語を削除するだけです。今日ユーザーフォーラムでこれを調べてみると、 |x: &u8|
機能する理由
おそらく関連している:私はこれにも遭遇しました(特にhuonの10月の例)。これは奇妙なことに他の方向に十分に壊れています。 つまり、明示的なアノテーションなしでのみ機能します: //github.com/rust-lang/rust/issues/22557
Triage:2018年にコンパイルされるようになりました。
2015エラー:
error[E0597]: `x` does not live long enough
--> src/main.rs:4:8
|
4 | f(&x);
| ^ borrowed value does not live long enough
5 | }
| - `x` dropped here while still borrowed
|
= note: values in a scope are dropped in the opposite order they are created
rustc: 1.32.0
これはどちらのエディションでも毎晩問題ではなくなったため、閉じる
最も参考になるコメント
Triage:2018年にコンパイルされるようになりました。
2015エラー:
rustc: 1.32.0