davecgh / go-spew

Implements a deep pretty printer for Go data structures to aid in debugging
ISC License
5.98k stars 361 forks source link

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

Open chenzhuoyu opened 1 year ago

chenzhuoyu commented 1 year ago

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

zavla commented 1 year ago

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

chenzhuoyu commented 1 year ago

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.

dwlnetnl commented 1 year ago

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

dwlnetnl commented 1 year ago

Dupe of #115