Rust: Lifetime Elision ist ohne explizite Typdeklaration zu gierig

Erstellt am 19. Feb. 2017  ·  3Kommentare  ·  Quelle: rust-lang/rust

Im nächsten Beispiel leiht sich der Abschluss den Wert länger aus, als er es tun sollte:

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

Was verursacht einen Kompilierungsfehler:

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

Wenn wir den Argumenttyp jedoch explizit deklarieren, funktioniert es wie erwartet:

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

Ich bin mir nicht sicher, ob das ein Fehler oder erwartetes Verhalten ist. Ich konnte auch keine Erklärung für diesen Effekt in der Dokumentation finden.

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

Hilfreichster Kommentar

Triage: kompiliert jetzt auf 2018.
Fehler 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

Alle 3 Kommentare

Um nur einen Begriff für Suchmaschinen fallen zu lassen: Als ich dies heute im Benutzerforum untersuchte, hatte ich den starken Eindruck, dass der Grund, warum |x: &u8| funktioniert, damit zusammenhängt, dass es als Hinweis für HRTB dient.

Möglicherweise verwandt: Ich bin auch auf dieses gestoßen (insbesondere das Oktoberbeispiel von huon), das seltsamerweise in die andere Richtung bricht; das heißt, es funktioniert nur _ohne_ die explizite Anmerkung: https://github.com/rust-lang/rust/issues/22557

Triage: kompiliert jetzt auf 2018.
Fehler 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

Geschlossen, da dies nachts in beiden Editionen kein Problem mehr ist

War diese Seite hilfreich?
0 / 5 - 0 Bewertungen