E0017

E0017#

Warning name: ambiguous_loop_argument

标识符的使用存在歧义。如果它指的是循环变量,请使用 as <id> 在模式中绑定它。如果它指的是变量在进入循环前的原始值,请在循环外部将其绑定到一个新的绑定器。

错误示例#

///|
fn main {
  let a : StringView = "asdf"
  loop a {
    [_, .. d] => {
      println(a)
      //      ^
      // Warning: The usage of 'a' is ambiguous. If it refers to the loop
      // variable, please use `as a` to bind it in the pattern. If it refers to
      // the original value of 'a' before entering the loop, please bind it to a
      // new binder outside the loop.
      continue d
    }
    [] => ()
  }
}

输出:

asdf
asdf
asdf
asdf

因为 a 指的是进入循环前的 a 的值,因此该值始终相同。

建议#

由于 loop 语法很快会被移除,若条件允许,建议优先将新代码改写为 for 循环。例如,这段代码可以写成:

let text : StringView = "asdf"
for i = 0; i < text.length(); i = i + 1 {
  println(text[i:])
}

如果你是在维护现有的 loop 代码,并且想引用随循环迭代而变化的循环变量,请使用 as <id> 在模式中绑定它。

///|
fn main {
  let a : StringView = "asdf"
  loop a {
    [_, .. d] as a => {
      println(a)
      continue d
    }
    [] => ()
  }
}

输出:

asdf
sdf
df
f

或者,如果你想在进入循环之前引用变量的原始值,可以显式地将其绑定到循环外的另一个名称。

///|
fn main {
  let a : StringView = "asdf"
  let b = a
  loop a {
    [_, .. d] => {
      println(b)
      continue d
    }
    [] => ()
  }
}

输出:

asdf
asdf
asdf
asdf