字典
除了内置的基本类型外,数组和字典也是内置类型。
map实现
从map的源代码定义看,map是通过2个struct实现的。
vlib/builtin/map.v
pub struct map {
// Number of bytes of a key
key_bytes int
// Number of bytes of a value
value_bytes int
mut:
// Highest even index in the hashtable
even_index u32
// Number of cached hashbits left for rehashing
cached_hashbits u8
// Used for right-shifting out used hashbits
shift u8
// Array storing key-values (ordered)
key_values DenseArray
// Pointer to meta-data:
// - Odd indices store kv_index.
// - Even indices store probe_count and hashbits.
metas &u32
// Extra metas that allows for no ranging when incrementing
// index in the hashmap
extra_metas u32
has_string_keys bool
hash_fn MapHashFn
key_eq_fn MapEqFn
clone_fn MapCloneFn
free_fn MapFreeFn
pub mut:
// Number of key-values currently in the hashmap
len int //字典的大小,也就是键值对的数量,这是map唯一可以对外直接访问的属性,只读
}
struct DenseArray {
key_bytes int
value_bytes int
mut:
cap int
len int
deletes u32 // count
// array allocated (with `cap` bytes) on first deletion
// has non-zero element when key deleted
all_deleted &u8 = unsafe { nil }
keys &u8 = unsafe { nil }
values &u8 = unsafe { nil }
}map定义
map的key除了string类型,也可以是其他任何类型。
string类型的key:
非string类型的key:
map字面量初始化,编译器会进行类型推断:
map.len返回字典的大小:
in操作符
判断某一个元素是否包含在map的key中:
遍历map
访问字典成员错误处理
if条件语句判断字典成员是否存在
删除字典成员
字典相关的源代码可以参考:vlib/builtin/map.v。
最后更新于
这有帮助吗?