E4118#
不能用映射模式匹配此类型。
您可以在自定义类型上使用映射模式,只要它们有一个方法 get,该方法返回给定键的可选值即可。
错误示例#
///|
priv struct MyMap {}
///|
test {
let map : MyMap = {}
match map {
{ "a": a, .. } => println("a: \{a}")
//^~~~~~~~~~~~~~
// Error: Please implement method `get` for type MyMap to match it with map pattern.
}
}
建议#
请根据错误消息中的建议实现 get 方法。
///|
priv struct MyMap {
entries : Map[String, Int]
}
///|
fn MyMap::get(self : MyMap, key : String) -> Int? {
self.entries.get(key)
}
///|
test {
let map : MyMap = { entries: { "a": 1, "b": 2, "c": 3 } }
match map {
{ "a": a, .. } => println("a: \{a}")
_ => println("missing")
}
}