😥 整理不易,此资源只针对正式星主开放,
还请入驻星球后再来观看。

GOLANG ROADMAP

阅读模式

  • 沉浸
  • 自动
  • 日常
首页
Go学习
  • Go学院

    • Go小课
    • Go小考
    • Go实战
    • 精品课
  • Go宝典

    • 在线宝典
    • B站精选
    • 推荐图书
    • 精品博文
  • Go开源

    • Go仓库
    • Go月刊
  • Go下载

    • 视频资源
    • 文档资源
Go求职
  • 求职服务

    • 内推互助
    • 求职助力
  • 求职刷题

    • 企业题库
    • 面试宝典
    • 求职面经
Go友会
  • 城市
  • 校园
推广返利 🤑
实验区
  • Go周边
消息
更多
  • 用户中心

    • 我的信息
    • 推广返利
  • 玩转星球

    • 星球介绍
    • 角色体系
    • 星主权益
  • 支持与服务

    • 联系星主
    • 成长记录
    • 常见问题
    • 吐槽专区
  • 合作交流

    • 渠道合作
    • 课程入驻
    • 友情链接
author-avatar

GOLANG ROADMAP


首页
Go学习
  • Go学院

    • Go小课
    • Go小考
    • Go实战
    • 精品课
  • Go宝典

    • 在线宝典
    • B站精选
    • 推荐图书
    • 精品博文
  • Go开源

    • Go仓库
    • Go月刊
  • Go下载

    • 视频资源
    • 文档资源
Go求职
  • 求职服务

    • 内推互助
    • 求职助力
  • 求职刷题

    • 企业题库
    • 面试宝典
    • 求职面经
Go友会
  • 城市
  • 校园
推广返利 🤑
实验区
  • Go周边
消息
更多
  • 用户中心

    • 我的信息
    • 推广返利
  • 玩转星球

    • 星球介绍
    • 角色体系
    • 星主权益
  • 支持与服务

    • 联系星主
    • 成长记录
    • 常见问题
    • 吐槽专区
  • 合作交流

    • 渠道合作
    • 课程入驻
    • 友情链接
  • Go真实面试题汇总系列

    • 《Map篇》
  • 宝典内容

    • 33. 如何实现一个线程安全的 map?
    • 35. Go map 的底层实现 ?
    • 37. map的key可以是哪些类型?可以嵌套map吗?
    • 39. 讲一下set的原理,Java 的HashMap和 go 的map底层原理
    • 53. go的map是线程安全的吗?
    • 87. go map并发安全问题,如何解决
    • 150. map遍历的时候每次顺序都是固定的吗?为什么?
    • 159. go的sync.Map了解吗
    • 166. golang中两个map对象如何比较。
    • 206. map如何顺序读取?
    • 227. gomap结构,并发安全否
    • 231. go的hashmap如何实现的
    • 243. go 的 map 与 sync.map
    • 250. sync.map与map的区别
    • 255. Go map的底层原理
    • 265. Map是线程安全的吗?怎么解决并发安全问题?
    • 266. sync.Map 怎么解决线程安全问题?看过源码吗?
    • 272. 问了sync.Map(我说我对sync.Pool比较熟,就说Pool了)
    • 278. map什么内容不能为key
    • 279. map和sync.Map
    • 287. 说一说go中的map
    • 288. map的优缺点,以及改进?
    • 290. go中的map?分段锁拆了几个分片?
    • 345. 借助额外的数据结构比如slice等,对key进行排序,遍历slice得到顺序输出
    • 351. go的map的底层数据结构,查询复杂度
    • 397. Go一般怎么取map?
    • 398.如果一个map没申请空间,去向里面取值,会发生什么情况
    • 401. go中如何使遍历map变得有序
    • 427. map取一个key,然后修改这个值,原map数据的值会不会变化,根据map存储的类型回答
    • 432. 实现map的方法除了哈希还有哪些?
    • 468. go map slice 实现(内存泄漏分析)

😥 整理不易,此资源只针对正式星主开放,
还请入驻星球后再来观看。

150. map遍历的时候每次顺序都是固定的吗?为什么?


企业题库解析小组

题目序号:(1490)

题目来源:字节跳动

频次:1

答案1:(jimyag)

package main

import "fmt"

func main() {
	fooMap := make(map[string]string)
	fooMap["foo1Key"] = "foo1Value"
	fooMap["foo2Key"] = "foo2Value"
	fooMap["foo3Key"] = "foo3Value"
	fooMap["foo4Key"] = "foo4Value"
	fooMap["foo5Key"] = "foo5Value"
	fooMap["foo6Key"] = "foo6Value"

	for k, v := range fooMap {
		fmt.Printf("k: %s ,v: %s \n", k, v)
	}
	//k: foo1Key ,v: foo1Value
	//k: foo2Key ,v: foo2Value
	//k: foo3Key ,v: foo3Value
	//k: foo4Key ,v: foo4Value
	//k: foo5Key ,v: foo5Value
	//k: foo6Key ,v: foo6Value

	//k: foo5Key ,v: foo5Value
	//k: foo6Key ,v: foo6Value
	//k: foo1Key ,v: foo1Value
	//k: foo2Key ,v: foo2Value
	//k: foo3Key ,v: foo3Value
	//k: foo4Key ,v: foo4Value

}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

结论:map遍历的时候每次的顺序是不一样的。

go tool compile -S main.go 
...初始化map...
0x0253 00595 (main.go:14)       LEAQ    type.map[string]string(SB), AX
        0x025a 00602 (main.go:14)       LEAQ    ""..autotmp_13+104(SP), BX
        0x025f 00607 (main.go:14)       LEAQ    ""..autotmp_10+152(SP), CX
        0x0267 00615 (main.go:14)       PCDATA  $1, $2
        0x0267 00615 (main.go:14)       CALL    runtime.mapiterinit(SB)
        0x026c 00620 (main.go:14)       JMP     786
        0x0271 00625 (main.go:14)       MOVQ    ""..autotmp_10+160(SP), DX
        0x0279 00633 (main.go:14)       MOVQ    (DX), SI
        0x027c 00636 (main.go:14)       MOVQ    SI, "".v.ptr+64(SP)
        0x0281 00641 (main.go:14)       MOVQ    (CX), AX
        0x0284 00644 (main.go:14)       MOVQ    8(DX), DX
... 
1
2
3
4
5
6
7
8
9
10
11
12
13
14

在初始化完成之后,调用了runtime.mapiterinit方法,在go1.18\src\runtime\map.go中找到此方法的实现,看一下源码的实现。

// mapiterinit initializes the hiter struct used for ranging over maps.
// The hiter struct pointed to by 'it' is allocated on the stack
// by the compilers order pass or on the heap by reflect_mapiterinit.
// Both need to have zeroed hiter since the struct contains pointers.
func mapiterinit(t *maptype, h *hmap, it *hiter) {
	if raceenabled && h != nil {
		callerpc := getcallerpc()
		racereadpc(unsafe.Pointer(h), callerpc, abi.FuncPCABIInternal(mapiterinit))
	}

	it.t = t
	if h == nil || h.count == 0 {
		return
	}

	if unsafe.Sizeof(hiter{})/goarch.PtrSize != 12 {
		throw("hash_iter size incorrect") // see cmd/compile/internal/reflectdata/reflect.go
	}
	it.h = h

	// grab snapshot of bucket state
	it.B = h.B
	it.buckets = h.buckets
	if t.bucket.ptrdata == 0 {
		// Allocate the current slice and remember pointers to both current and old.
		// This preserves all relevant overflow buckets alive even if
		// the table grows and/or overflow buckets are added to the table
		// while we are iterating.
		h.createOverflow()
		it.overflow = h.extra.overflow
		it.oldoverflow = h.extra.oldoverflow
	}

	// decide where to start
	r := uintptr(fastrand())
	if h.B > 31-bucketCntBits {
		r += uintptr(fastrand()) << 31
	}
	it.startBucket = r & bucketMask(h.B)
	it.offset = uint8(r >> h.B & (bucketCnt - 1))

	// iterator state
	it.bucket = it.startBucket

	// Remember we have an iterator.
	// Can run concurrently with another mapiterinit().
	if old := h.flags; old&(iterator|oldIterator) != iterator|oldIterator {
		atomic.Or8(&h.flags, iterator|oldIterator)
	}

	mapiternext(it)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52

通过对 mapiterinit 方法阅读,可得知其主要用途是在 map 进行遍历迭代时进行初始化动作。共有三个形参,用于读取当前哈希表的类型信息、当前哈希表的存储信息和当前遍历迭代的数据。

咱们关注到源码中 fastrand 的部分,这个方法名,是不是迷之眼熟。没错,它是一个生成随机数的方法。再看看上下文

// decide where to start
	r := uintptr(fastrand())
	if h.B > 31-bucketCntBits {
		r += uintptr(fastrand()) << 31
	}
	it.startBucket = r & bucketMask(h.B)
	it.offset = uint8(r >> h.B & (bucketCnt - 1))
1
2
3
4
5
6
7

在这段代码中,它生成了随机数。用于决定从哪里开始循环迭代。更具体的话就是根据随机数,选择一个桶位置作为起始点进行遍历迭代

因此每次重新 for range map,你见到的结果都是不一样的。那是因为它的起始位置根本就不固定!

参考:[为什么遍历 Go map 是无序的? - 云+社区 - 腾讯云 (tencent.com)](