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.pull/10616/head
parent
184e8e8923
commit
7ae106d14a
8
id.go
8
id.go
|
@ -111,6 +111,14 @@ func (i ID) String() string {
|
||||||
return string(enc)
|
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.
|
// UnmarshalJSON implements JSON unmarshaller for IDs.
|
||||||
func (i *ID) UnmarshalJSON(b []byte) error {
|
func (i *ID) UnmarshalJSON(b []byte) error {
|
||||||
if b[0] == '"' {
|
if b[0] == '"' {
|
||||||
|
|
19
id_test.go
19
id_test.go
|
@ -3,6 +3,7 @@ package platform_test
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
"reflect"
|
"reflect"
|
||||||
"testing"
|
"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) {
|
func BenchmarkIDEncode(b *testing.B) {
|
||||||
var id platform.ID
|
var id platform.ID
|
||||||
id.DecodeFromString("5ca1ab1eba5eba11")
|
id.DecodeFromString("5ca1ab1eba5eba11")
|
||||||
|
|
Loading…
Reference in New Issue