go-spew icon indicating copy to clipboard operation
go-spew copied to clipboard

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

Open chenzhuoyu opened this issue 2 years ago • 4 comments

Repro:

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

chenzhuoyu avatar Jul 07 '22 06:07 chenzhuoyu

A workaround is: func main() { spew.Dump(&X{1: 2}) }

zavla avatar Jul 24 '22 09:07 zavla

A workaround is: func main() { spew.Dump(&X{1: 2}) }

Not really. Sometimes the map is not directly accessable, and maybe nested in a deep structure.

chenzhuoyu avatar Nov 17 '22 08:11 chenzhuoyu

I've fixed this issue in my fork of the package: https://github.com/spewerspew/spew/commit/62a6506637ab035cd8626d40cf3d7f74d8dcd4d6

dwlnetnl avatar May 13 '23 23:05 dwlnetnl

Dupe of #115

dwlnetnl avatar May 13 '23 23:05 dwlnetnl