E0013#
这个表达式的类型包含未解析的类型变量。
当编译器遇到无法从上下文确定的类型变量时,将会出现此错误。类型变量是应由编译器推断的类型的占位符。
常见情况:
编写没有明确类型注释的局部函数
创建空集合(数组,选项),而未指定其元素类型。
当编译器无法解析这些类型变量时,它将其默认为 Unit
类型,这可能并不是你所期望的。
错误示例#
pub fn f1() -> Unit {
fn f(x) {
// ^ Warning: The type of this expression is Option[_/0], which contains
// unresolved type variables. The type variable is default to
// Unit.
match x {
None => ()
Some(a) => println(a)
}
}
f(None)
}
pub fn f2() -> Unit {
fn f(x : Array[_]) -> Int {
// ^ Warning: The type of this expression is Array[_/0], which contains
// unresolved type variables. The type variable is default to
// Unit.
x.length()
}
println(f([]))
}
fn main {
let a = []
// ^^ Warning: The type of this expression is Array[_/0], which contains
// unresolved type variables. The type variable is default to Unit.
println(a.length())
let b = None
// ^^ Warning: The type of this expression is Option[_/0], which contains
// unresolved type variables. The type variable is default to Unit.
println(b.is_empty())
}
建议#
要修复这个警告,你可以:
为局部类型函数参数添加类型注释。例如:
///| pub fn f1() -> Unit { fn f(x : Int?) { match x { None => () Some(a) => println(a) } } f(None) } ///| pub fn f2() -> Unit { fn f(x : Array[Int]) -> Int { x.length() } println(f([])) }
显式指定变量或集合元素的类型。
///| fn example_explicit_variable_types() -> Unit { let a : Array[Int] = [] println(a.length()) let b : Int? = None println(b.is_empty()) }
或者,等效地,在集合创建时添加类型注释。
///| fn example_annotated_collections() -> Unit { let a = ([] : Array[Int]) println(a.length()) let b = (None : Int?) println(b.is_empty()) }
通过使用提供足够的上下文。
///| fn example_context_usage() -> Unit { fn f(x) { match x { None => () Some(a) => println(a + 1) // ^^^^^ through this usage, the compiler can infer the // type of `x` is `Option[Int]`. } } f(None) }