或模式
当多个分支存在共享数据且处理逻辑相同时,单独处理会显得冗余。例如,本示例定义枚举类型RGB
和用于提取绿色通道值的get_green
函数。
通过或模式可将RGB
和RGBA
分支合并处理。在或模式中,子模式可引入新变量,但所有子模式的变量必须类型相同且命名一致,该限制确保后续能统一处理这些变量。
fn main {
let array = [1, 2, 3, 4, 5, 6]
let [a, b, ..] = array
let [.., c, d] = array
let [e, .., f] = array
println("a: \{a}, b: \{b}")
println("c: \{c}, d: \{d}")
println("e: \{e}, f: \{f}")
println("sum of array: \{sum(array[:])}")
}
fn sum(array : ArrayView[Int]) -> Int {
match array {
[] => 0
[x, .. as xs] => x + sum(xs)
}
}