1
0
mirror of https://github.com/golang/go synced 2024-11-21 23:44:39 -07:00

gob: isZero for struct values

Fixes #2577.

R=golang-dev, r, gri
CC=golang-dev
https://golang.org/cl/5492058
This commit is contained in:
Rob Pike 2011-12-16 11:33:57 -08:00
parent bf6dd2db04
commit 4fb5f5449a
2 changed files with 35 additions and 0 deletions

View File

@ -483,6 +483,13 @@ func isZero(val reflect.Value) bool {
return val.Float() == 0
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
return val.Uint() == 0
case reflect.Struct:
for i := 0; i < val.NumField(); i++ {
if !isZero(val.Field(i)) {
return false
}
}
return true
}
panic("unknown type in isZero " + val.Type().String())
}

View File

@ -13,6 +13,7 @@ import (
"io"
"strings"
"testing"
"time"
)
// Types that implement the GobEncoder/Decoder interfaces.
@ -526,3 +527,30 @@ func TestGobEncoderExtraIndirect(t *testing.T) {
t.Errorf("got = %q, want %q", got, gdb)
}
}
// Another bug: this caused a crash with the new Go1 Time type.
type TimeBug struct {
T time.Time
S string
I int
}
func TestGobEncodeTime(t *testing.T) {
x := TimeBug{time.Now(), "hello", -55}
b := new(bytes.Buffer)
enc := NewEncoder(b)
err := enc.Encode(x)
if err != nil {
t.Fatal("encode:", err)
}
var y TimeBug
dec := NewDecoder(b)
err = dec.Decode(&y)
if err != nil {
t.Fatal("decode:", err)
}
if x != y {
t.Fatal("%v != %v", x, y)
}
}