From 7ae106d14a8b4273eaa43b5807f50f36fe278ddc Mon Sep 17 00:00:00 2001 From: Mark Rushakoff Date: Wed, 31 Oct 2018 14:26:17 -0700 Subject: [PATCH] chore: add GoString method to platform.ID While debugging, I was printing out some structs with %#v and found that Go would format the structs' IDs as uint64s instead of with the String method. That behavior needlessly made my debugging more difficult. Before, %#v would format a type with an ID like: {ID:0x2def021097c6000} After: {ID:"02def021097c6000"} They look similar, but a search for the string ID would not match the uint64 default formatting. --- id.go | 8 ++++++++ id_test.go | 19 +++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/id.go b/id.go index 219915bd39..c9154a63a8 100644 --- a/id.go +++ b/id.go @@ -111,6 +111,14 @@ func (i ID) String() string { return string(enc) } +// GoString formats the ID the same as the String method. +// Without this, when using the %#v verb, an ID would be printed as a uint64, +// so you would see e.g. 0x2def021097c6000 instead of 02def021097c6000 +// (note the leading 0x, which means the former doesn't show up in searches for the latter). +func (i ID) GoString() string { + return `"` + i.String() + `"` +} + // UnmarshalJSON implements JSON unmarshaller for IDs. func (i *ID) UnmarshalJSON(b []byte) error { if b[0] == '"' { diff --git a/id_test.go b/id_test.go index 8b070bf8b5..7c28f1c0bc 100644 --- a/id_test.go +++ b/id_test.go @@ -3,6 +3,7 @@ package platform_test import ( "bytes" "encoding/json" + "fmt" "reflect" "testing" @@ -193,6 +194,24 @@ func TestValid(t *testing.T) { } } +func TestID_GoString(t *testing.T) { + type idGoStringTester struct { + ID platform.ID + } + var x idGoStringTester + + const idString = "02def021097c6000" + if err := x.ID.DecodeFromString(idString); err != nil { + t.Fatal(err) + } + + sharpV := fmt.Sprintf("%#v", x) + want := `platform_test.idGoStringTester{ID:"` + idString + `"}` + if sharpV != want { + t.Fatalf("bad GoString: got %q, want %q", sharpV, want) + } +} + func BenchmarkIDEncode(b *testing.B) { var id platform.ID id.DecodeFromString("5ca1ab1eba5eba11")