davecgh / go-spew

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

Incorrect representation of pointer values when nil #4

Closed kortschak closed 11 years ago

kortschak commented 11 years ago

The following snippet shows that pointers are represented as double pointers when they are nil. I do not think this is intended:

package main

import (
    "github.com/davecgh/go-spew/spew"
)

type A struct {
    P *A
}

func main() {
    spew.Dump(A{})
    spew.Dump(A{P: &A{}})
}

Output:

(main.A) {
 P: (**main.A)()(<nil>)
}
(main.A) {
 P: (*main.A)(0xf840043148)({
  P: (**main.A)()(<nil>)
 })
}
kortschak commented 11 years ago

Fixed by the following change:

diff --git a/spew/dump.go b/spew/dump.go
index 361e90e..db7ecbd 100644
--- a/spew/dump.go
+++ b/spew/dump.go
@@ -66,11 +66,11 @@ func (d *dumpState) dumpPtr(v reflect.Value) {
    indirects := 0
    ve := v
    for ve.Kind() == reflect.Ptr {
-       indirects++
        if ve.IsNil() {
            nilFound = true
            break
        }
+       indirects++
        addr := ve.Pointer()
        pointerChain = append(pointerChain, addr)
        if pd, ok := d.pointers[addr]; ok && pd < d.depth {
kortschak commented 11 years ago

Test patch here: https://gist.github.com/4521156

davecgh commented 11 years ago

Thanks for the report and the patch + tests. I'll apply them shortly with a few modifications as I don't think there should be empty parenthesis when there is no pointer information to display. That is already handled in the Formatter, but I forgot to apply it to the Dump code as well.

davecgh commented 11 years ago

This issue is resolved with tests added as of commit e892c84d386b41f1a63a4ec7b4b35bc69b093ac4.