Rust: Elisi seumur hidup terlalu serakah tanpa deklarasi tipe eksplisit

Dibuat pada 19 Feb 2017  ·  3Komentar  ·  Sumber: rust-lang/rust

Dalam contoh berikutnya penutupan meminjam nilai lebih lama dari yang seharusnya:

fn main () {
    let f = |y| { println!("{}", y); };
    let x = 4u8;
    f(&x);
}

Yang menyebabkan kesalahan kompilasi:

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

Namun, jika kita mendeklarasikan tipe argumen secara eksplisit, itu berfungsi seperti yang diharapkan:

fn main () {
    let f = |y: &u8| { println!("{}", y); };
    let x = 4u8;
    f(&x);
}

Tidak yakin apakah itu bug atau perilaku yang diharapkan. Saya juga tidak dapat menemukan penjelasan tentang efek ini dalam dokumentasi.

Meta

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
A-closures A-inference A-lifetimes C-bug NLL-fixed-by-NLL T-compiler

Komentar yang paling membantu

Triage: sekarang dikompilasi pada 2018.
kesalahan 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

Semua 3 komentar

Hanya untuk menjatuhkan istilah untuk mesin pencari: menjelajahi ini hari ini di forum pengguna, saya mendapat kesan kuat bahwa alasan |x: &u8| bekerja mungkin terkait dengan itu yang berfungsi sebagai petunjuk untuk HRTB.

Mungkin terkait: Saya juga mengalami yang ini (khususnya contoh oktober huon), yang anehnya pecah ke arah lain; yaitu, ini hanya berfungsi _tanpa_ anotasi eksplisit: https://github.com/rust-lang/rust/issues/22557

Triage: sekarang dikompilasi pada 2018.
kesalahan 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

Penutupan karena ini tidak lagi menjadi masalah di malam hari di kedua edisi

Apakah halaman ini membantu?
0 / 5 - 0 peringkat