#141·go-spew

映射的自定义 `String()` 方法收到了无效的接收者值

作者: chenzhuoyu创建于 2022年7月7日更新于 2023年5月13日
go
package main
import (
"fmt"
"GitHub.com/davecgh/go-spew/spew"
)
type X map[int]int
func (x X) String() string {
return fmt.Sprintf("{M1:%d}", len(x))
}
func main() {
spew.Dump(X{1: 2})
}
输出:
(main.X) (len=1) (PANIC=runtime error: invalid memory address or nil pointer dereference) {
(int) 1: (int) 2
}
当获取接收器 `x` 的 `len()` 时,会发生 Panic,因为这是一个无效指针。

内容来源: davecgh/go-spew