Mi informacion de contacto
Correo[email protected]
2024-07-12
한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina
map es una colección desordenada de pares clave-valor en 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] = "老五"
Elimine elementos según claves y no se informará ningún error al eliminar claves inexistentes.
delete(mapName, key)
// 假设map名为m,key为int,value为string
delete(m, 5)
Para modificar, puede modificar directamente el valor correspondiente a la clave especificada.
mapName[key] = newValue
// 假设map名为m,key为int,value为string
m[5] = "五"
Obtenga el valor de acuerdo con la clave, está bien si se encuentra el bit de bandera, el tipo es booleano
Si no se encuentra el valor, no se informará ningún error y se devolverá un valor nulo del tipo correspondiente.
value, ok := mapName[key]
if !ok {
fmt.Println(ok)
}
Nota: el recorrido del mapa no está ordenado
for key, value := range myMap {
// 处理每对键值
}
// 例子
for i, s := range m {
fmt.Println(i, s)
}
La esencia subyacente del mapa en el lenguaje golang es utilizar
hashmap
está implementado, por lo que el mapa es esencialmente哈希表
。
哈希表
es un uso哈希函数
Organice los datos en estructuras de datos que admitan una inserción y búsqueda rápidas.
哈希函数
, también conocida como función hash, es una función que convierte una entrada de cualquier longitud (como una cadena) en una salida de longitud fija mediante un algoritmo hash específico. Los valores hash generalmente se almacenan en forma de matriz para garantizar el rendimiento del acceso a los valores hash.
Si el rango de la entrada excede el rango de la salida asignada, puede causar que diferentes entradas obtengan la misma salida.
哈希冲突
。Generalmente hay dos formas de solucionar este problema:
开放地址法
y拉链法
Método de dirección abierta:
Las estructuras de datos generalmente se implementan mediante matrices.
defecto:
Este enfoque requiere más espacio para resolver conflictos porque no solo se almacenan los datos, sino que también se requiere espacio adicional para resolver las colisiones.
Método de cremallera (Go Language Map utiliza este método):
Las matrices y las listas enlazadas se suelen utilizar como estructuras de datos subyacentes.
Una lista vinculada vinculada en diferentes índices de una matriz también se denomina depósito.
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 // 下一个可用的溢出桶地址
}
En el código fuente, el tipo bmap tiene solo un campo tophash.Pero durante la compilación, el compilador Go inyectará automáticamente la clave, el valor y otras estructuras correspondientes de acuerdo con el código del usuario.
Mapa de superficie
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.
}
mapa b real
// 编译期间会动态地创建一个新的结构:
type bmap struct {
topbits [8]uint8 // 这里存储哈希值的高八位,用于在确定key的时候快速试错,加快增删改查寻址效率,有时候也叫tophash
keys [8]keytype // 存储key的数组,这里bmap最多存储8个键值对
elems [8]valuetype // 存储value的数组,这里bmap也最多存储8个键值对
...
overflow uintptr // 溢出桶指针
}
En el lenguaje Go, la expansión del mapa se realiza automáticamente para mantener el rendimiento del mapa.
Primero, al escribir, el mapa pasa.runtime.mapassign
Determinar si se necesita expansión
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)
}
Según el código anterior, existen dos condiciones para juzgar la expansión:
overLoadFactor(h.count+1, h.B)
, factor de carga = número de elementos ÷ número de cubostooManyOverflowBuckets(h.noverflow, h.B))
Método de expansión:
Cuando el factor de carga es demasiado grande, se crea un nuevo depósito. La longitud del nuevo depósito es el doble de la longitud original y luego los datos del depósito anterior se mueven al nuevo depósito.
No hay muchos datos, pero hay demasiados depósitos desbordados.Durante la expansión, la cantidad de depósitos permanece sin cambios. Se vuelven a realizar operaciones de reubicación similares a la expansión incremental y los pares clave-valor sueltos se reorganizan para aumentar el uso del depósito y garantizar un acceso más rápido.
Pasos de expansión:
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)
}
...
}
渐进式驱逐
Migrar pares clave-valor. Esto significa que durante la expansión, la matriz de depósitos anterior y la nueva matriz de depósitos existirán al mismo tiempo, los pares clave-valor recién insertados se colocarán directamente en el depósito nuevo y el acceso al depósito anterior desencadenará una operación de migración.// 进入后是一个简单的判断,之后的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
oint64
。sync.Map
O implemente su propio mapa simultáneamente seguro.