Go 语言 FAQ

Table of Contents

1. map

1.1. Key

map 中的 key 必须是可以判定相等的类型。不建议把浮点数作为 key,最坏的情况下 NaN 和任何浮点数都不同。

1.2. 值还是引用?

map 是个引用类型(hash 表)。因此使用 map 必须初始化(否则值默认为 nil)。

1.3. 迭代

map 迭代顺序是不确定的。

1.4. map 中删除元素是否安全?

安全1

for key := range m {
    if key.expired() {
        delete(m, key)
    }
}
  1. Go map 是使用 hash 表实现的,并不是 tree
  2. delete 并没有实际的删除一个元素,只是设置一个标记,也就是说,delete 并不会减少 map 空间的大小2。 并且允许删除一个不存在的 key。
  3. 只有 map=nil 才会释放空间

2. json.marshal

[]byte json marshal 会被自动做个 base64 编码,https://pkg.go.dev/encoding/json#Marshal

Array and slice values encode as JSON arrays, except that []byte encodes as a base64-encoded string, and a nil slice encodes as the null JSON value.

Footnotes:

First created: 2020-10-06 16:21:47
Last updated: 2022-12-11 Sun 12:49
Power by Emacs 29.0.91 (Org mode 9.6.6)