Rust: 没有显式类型声明的生命周期省略太贪婪了

创建于 2017-02-19  ·  3评论  ·  资料来源: rust-lang/rust

在下一个例子中,闭包借用值的时间比它应该做的要长:

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

最有用的评论

分类:现在编译于 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

所有3条评论

只是为了搜索引擎放弃一个术语:今天在用户论坛上探索这个,我强烈的印象是|x: &u8|起作用的原因可能与它作为 HRTB 的提示有关。

可能相关:我也遇到了这个(特别是 huon 十月的例子),奇怪的是,它在另一个方向上中断了; 也就是说,它只适用于_没有_显式注释: https :

分类:现在编译于 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

关闭,因为这在任何一个版本中都不再是每晚的问题

此页面是否有帮助?
0 / 5 - 0 等级