minhas informações de contato
Correspondência[email protected]
2024-07-12
한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina
map é uma coleção não ordenada de pares de valores-chave no formato kv
var name map[key_type]value_type
// 方式一
var m map[int]string = map[int]string{}
// 方式二
m := map[int]string{
1 : "老一",
2 : "老二",
3 : "老三",
}
// 方式三:5代表容量,也就是在内存中占用多大的空间,可以省略
m := make(map[int]string,5)
mapName[key] = value
// 假设map名为m,key为int,value为string
m[5] = "老五"
Exclua elementos com base em chaves e nenhum erro será relatado ao excluir chaves inexistentes.
delete(mapName, key)
// 假设map名为m,key为int,value为string
delete(m, 5)
Para modificar, você pode modificar diretamente o valor correspondente à chave especificada.
mapName[key] = newValue
// 假设map名为m,key为int,value为string
m[5] = "五"
Obtenha o valor de acordo com a chave, ok é o bit do sinalizador se for encontrado, o tipo é Booleano
Se o valor não for encontrado, nenhum erro será relatado e um valor nulo do tipo correspondente será retornado.
value, ok := mapName[key]
if !ok {
fmt.Println(ok)
}
Nota: a travessia do mapa não é ordenada
for key, value := range myMap {
// 处理每对键值
}
// 例子
for i, s := range m {
fmt.Println(i, s)
}
A essência subjacente do mapa na linguagem golang é usar
hashmap
é implementado, então map é essencialmente哈希表
。
哈希表
é um uso哈希函数
Organize os dados em estruturas de dados que suportam inserção e pesquisa rápidas.
哈希函数
, também conhecida como função hash, é uma função que converte uma entrada de qualquer comprimento (como uma string) em uma saída de comprimento fixo por meio de um algoritmo hash específico. Os valores de hash geralmente são armazenados em formato de array para garantir o desempenho de acesso dos valores de hash.
Se o intervalo da entrada exceder o intervalo da saída mapeada, isso poderá fazer com que entradas diferentes obtenham a mesma saída.
哈希冲突
。Geralmente existem duas maneiras de resolver esse problema:
开放地址法
e拉链法
Método de endereço aberto:
Estruturas de dados geralmente são implementadas usando arrays
deficiência:
Essa abordagem requer mais espaço para resolver conflitos porque não apenas os dados são armazenados, mas também é necessário espaço adicional para resolver colisões.
Método Zipper (o mapa de idiomas go usa este método):
Matrizes e listas vinculadas são geralmente usadas como estruturas de dados subjacentes
Uma lista vinculada vinculada a diferentes índices de um array também é chamada de bucket.
type hmap struct {
count int // 当前哈希表中的元素数量,即键值对数量,可用内置函数len()获取
flags uint8 // 标志位,标记map状态和属性的字段,如正在迭代等状态
B uint8 // 表示哈希表桶(buckets)的数量为2的B次方
noverflow uint16 // 溢出桶的大致数量,扩容时会用到
hash0 uint32 // 哈希种子,对key做哈希是加入种子计算哈希值,确保map安全性
buckets unsafe.Pointer // 存储桶数组的指针
oldbuckets unsafe.Pointer // 扩容时用于保存旧桶数组的指针 , 大小为新桶数组的一半
nevacuate uintptr // 扩容时的迁移进度器,迁移桶下标小于此值说明完成迁移
extra *mapextra // 溢出桶的指针,指向mapextra结构体,用于存储一些额外的字段和信息
}
// mapextra 处理桶溢出的结构体
type mapextra struct {
overflow *[]*bmap // 溢出桶数组指针,仅当key和elem非指针时才使用
oldoverflow *[]*bmap // 旧的溢出桶数组指针,仅当key和elem非指针时才使用
nextOverflow *bmap // 下一个可用的溢出桶地址
}
No código-fonte, o tipo bmap possui apenas um campo tophash.Porém, durante a compilação, o compilador Go injetará automaticamente a chave, o valor e outras estruturas correspondentes de acordo com o código do usuário.
Bmap de superfície
type bmap struct {
// tophash generally contains the top byte of the hash value
// for each key in this bucket. If tophash[0] < minTopHash,
// tophash[0] is a bucket evacuation state instead.
tophash [bucketCnt]uint8
// Followed by bucketCnt keys and then bucketCnt elems.
// NOTE: packing all the keys together and then all the elems together makes the
// code a bit more complicated than alternating key/elem/key/elem/... but it allows
// us to eliminate padding which would be needed for, e.g., map[int64]int8.
// Followed by an overflow pointer.
}
bmap real
// 编译期间会动态地创建一个新的结构:
type bmap struct {
topbits [8]uint8 // 这里存储哈希值的高八位,用于在确定key的时候快速试错,加快增删改查寻址效率,有时候也叫tophash
keys [8]keytype // 存储key的数组,这里bmap最多存储8个键值对
elems [8]valuetype // 存储value的数组,这里bmap也最多存储8个键值对
...
overflow uintptr // 溢出桶指针
}
Na linguagem Go, a expansão do mapa é realizada automaticamente para manter o desempenho do mapa.
Primeiro, ao escrever, o mapa passaruntime.mapassign
Determine se a expansão é necessária
func mapassign(t *maptype, h *hmap, key unsafe.Pointer) unsafe.Pointer {
...
// If we hit the max load factor or we have too many overflow buckets,
// and we're not already in the middle of growing, start growing.
if !h.growing() && (overLoadFactor(h.count+1, h.B) || tooManyOverflowBuckets(h.noverflow, h.B)) {
hashGrow(t, h)
goto again // Growing the table invalidates everything, so try again
}
...
}
// overLoadFactor reports whether count items placed in 1<<B buckets is over loadFactor.
func overLoadFactor(count int, B uint8) bool {
return count > bucketCnt && uintptr(count) > loadFactorNum*(bucketShift(B)/loadFactorDen)
}
func tooManyOverflowBuckets(noverflow uint16, B uint8) bool {
if B > 15 {
B = 15
}
return noverflow >= uint16(1)<<(B&15)
}
De acordo com o código acima, existem duas condições para julgar a expansão:
overLoadFactor(h.count+1, h.B)
, fator de carga = número de elementos ÷ número de bucketstooManyOverflowBuckets(h.noverflow, h.B))
Método de expansão:
Quando o fator de carga é muito grande, um novo intervalo é criado. O novo comprimento do intervalo é o dobro do comprimento original e, em seguida, os dados do intervalo antigo são movidos para o novo intervalo.
Não há muitos dados, mas há muitos buckets de estouro.Durante a expansão, o número de buckets permanece inalterado. Operações de realocação semelhantes à expansão incremental são executadas novamente e pares de valores-chave soltos são reorganizados para aumentar o uso do bucket e garantir acesso mais rápido.
Etapas de expansão:
func hashGrow(t *maptype, h *hmap) {
...
// 原有桶设置给oldbuckets
oldbuckets := h.buckets
// 创建新桶
newbuckets, nextOverflow := makeBucketArray(t, h.B+bigger, nil)
flags := h.flags &^ (iterator | oldIterator)
if h.flags&iterator != 0 {
flags |= oldIterator
}
// commit the grow (atomic wrt gc)
h.B += bigger
h.flags = flags
h.oldbuckets = oldbuckets
h.buckets = newbuckets
h.nevacuate = 0
h.noverflow = 0
...
}
// 这个是mapdelete函数中的处理迁移的位置
func mapassign(t *maptype, h *hmap, key unsafe.Pointer) unsafe.Pointer {
...
if h.growing() {
//
growWork(t, h, bucket)
}
...
}
渐进式驱逐
Migre pares de valores-chave. Isso significa que durante a expansão, a matriz de bucket antiga e a nova matriz de bucket existirão ao mesmo tempo, os pares de valores-chave recém-inseridos serão colocados diretamente no novo bucket e o acesso ao bucket antigo acionará uma operação de migração.// 进入后是一个简单的判断,之后的evacuate是核心逻辑处理,特别多,感兴趣自己看源码
func growWork(t *maptype, h *hmap, bucket uintptr) {
// make sure we evacuate the oldbucket corresponding
// to the bucket we're about to use
evacuate(t, h, bucket&h.oldbucketmask())
// evacuate one more oldbucket to make progress on growing
if h.growing() {
evacuate(t, h, h.nevacuate)
}
}
int
ouint64
。sync.Map
Ou implemente seu próprio mapa simultaneamente seguro.