#141·go-spew

Custom `String()` method of maps got invalid receiver value

Author: chenzhuoyuCreated Jul 7, 2022Updated May 13, 2023

Repro:

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})
}

Output:

(main.X) (len=1) (PANIC=runtime error: invalid memory address or nil pointer dereference){
 (int) 1: (int) 2
}

Panic occures when taking the len() of the receiver x, which is an invalid pointer.

This happens on all versions of go I installed (1.16 to 1.18).