Rust: 类型推断建议修正不存在的变量 `__next`

创建于 2018-05-28  ·  3评论  ·  资料来源: rust-lang/rust

此代码:(游乐场链接

fn main() {
    let tiles = Default::default();
    for row in &mut tiles {
        for tile in row {
            *tile = 0;
        }
    }

    let tiles: [[usize; 3]; 3] = tiles;
}

失败并出现此错误:

error[E0282]: type annotations needed
 --> src/main.rs:5:13
  |
4 |         for tile in row {
  |             ---- consider giving `__next` a type
5 |             *tile = 0;
  |             ^^^^^ cannot infer type for `_`

类型推断(理所当然地)在此代码上失败。 但是,它建议修复的变量称为__next并且实际上并不存在于我的代码中。 它可能是编译器生成的一些内部变量。

A-diagnostics C-bug

所有3条评论

好吧,在这种情况下拒绝命名变量很简单——

diff --git a/src/librustc/infer/error_reporting/need_type_info.rs b/src/librustc/infer/error_reporting/need_type_info.rs
index 7352c14..25bfb3e 100644
--- a/src/librustc/infer/error_reporting/need_type_info.rs
+++ b/src/librustc/infer/error_reporting/need_type_info.rs
@@ -131,7 +131,10 @@ impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
             labels.clear();
             labels.push((pattern.span, format!("consider giving this closure parameter a type")));
         } else if let Some(pattern) = local_visitor.found_local_pattern {
-            if let Some(simple_name) = pattern.simple_name() {
+            // don't put internal desugared-loop identifier in user-facing
+            // message (Issue #51116)
+            let simple_name = pattern.simple_name().filter(|n| n.as_str() != "__next");
+            if let Some(simple_name) = simple_name {
                 labels.push((pattern.span, format!("consider giving `{}` a type", simple_name)));
             } else {
                 labels.push((pattern.span, format!("consider giving the pattern a type")));

但更根本的是,这不是在循环上设置的好标签:我们没有对循环变量进行类型注释的语法。

__next来自脱糖:

https://github.com/rust-lang/rust/blob/5ae5361cdd7b4e518d6733fb726521563d5b4cfa/src/librustc/hir/lowering.rs#L3355 -L3501

但更根本的是,这不是在循环上设置的好标签:我们没有对循环变量进行类型注释的语法。

同意,我们应该检查这个案例。

已在 #52418 中修复。

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