14. Map 与 Set
Map[K, V] 和 Set[T] 是内建的持久容器:每次「修改」都返回新容器,原值不变。
没有字面量语法,操作都在 std/map 与 std/set 模块里。迭代顺序 = 插入顺序
(JVM 与 native 一致)。
use std/map
use std/set
pub fn main() -> Unit !io = {
let m = map.insert(map.insert(map.empty(), "a", 1), "b", 2)
println(to_string(map.get(m, "a")))
println(to_string(map.get(m, "z")))
println(to_string(map.keys(m)))
let s = set.from([3, 1, 2, 1, 3])
println(to_string(set.len(s)))
println(to_string(set.has(s, 2)))
}
在 Playground 打开
Some(1)
None
["a", "b"]
3
true
键可以是任何具结构相等的类型(Int/String/元组/ADT/record)。map.get 返回
Option[V]——查不到是 None,不是异常。相等与顺序无关:键值相同的两个 Map 相等。