E4165#
Compiler diagnostic name: missing_op_as_view.
数组模式匹配缺少 op_as_view 方法。
像 [head, ..tail] 这样的开放数组模式需要目标值能够为模式中的 .. 部分提供视图。op_as_view 是编译器为 _[_:_] 视图操作符使用的内部名称;在源码中,这个操作通过给兼容的方法标注 #alias("_[_:_]") 来提供。
错误示例#
下面的示例尝试对 Int 使用开放数组模式,但 Int 并不提供 op_as_view:
///|
///|
fn first_and_rest(value : Int) -> Int {
match value {
[head, .. _tail] => head
_ => 0
}
}
///|
test {
ignore(first_and_rest)
}
MoonBit 会报告一个错误。
建议#
请使用提供视图操作的类数组值。定义这个操作时,给方法标注 #alias("_[_:_]"),例如:
#alias("_[_:_]")
fn Type::view(self : Type, start? : Int = 0, end? : Int) -> View {
...
}
修复后的示例使用 Array[Int],它已经提供了这个操作:
///|
///|
fn first_or_zero(values : Array[Int]) -> Int {
match values {
[head, .. _tail] => head
[] => 0
}
}
///|
test {
inspect(first_or_zero([1, 2, 3]), content="1")
inspect(first_or_zero([]), content="0")
}