Skip to content

Commit

Permalink
Back to int64 because driver.Value doesn't support unsigned types.
Browse files Browse the repository at this point in the history
  • Loading branch information
Kugelschieber committed Nov 9, 2021
1 parent 8fe4053 commit e09a353
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 9 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ Consider the following struct:

```
type User struct {
Id uint64 `json:"id"`
Id int64 `json:"id"`
Username string `json:"username"`
}
```
Expand All @@ -46,7 +46,7 @@ type User struct {
}
```

Notice that the `uint64` ID got replaced by the `hide.ID`, which internally is represented as an `uint64` as well, but implements the marshal interface.
Notice that the `int64` ID got replaced by the `hide.ID`, which internally is represented as an `int64` as well, but implements the marshal interface.
This allows you to cast between them and use `hide.ID` as a replacement. The resulting JSON changes to the following:

```
Expand Down
8 changes: 4 additions & 4 deletions id.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@ import (
"strings"
)

// ID type that can be used as an replacement for uint64.
// ID type that can be used as an replacement for int64.
// It is converted to/from a hash value when marshalled to/from JSON.
// Value 0 is considered null.
type ID uint64
type ID int64

// Scan implements the Scanner interface.
func (hide *ID) Scan(value interface{}) error {
Expand All @@ -19,7 +19,7 @@ func (hide *ID) Scan(value interface{}) error {
return nil
}

id, ok := value.(uint64)
id, ok := value.(int64)

if !ok {
return errors.New("unexpected type")
Expand All @@ -35,7 +35,7 @@ func (hide ID) Value() (driver.Value, error) {
return nil, nil
}

return uint64(hide), nil
return int64(hide), nil
}

// MarshalJSON implements the encoding json interface.
Expand Down
6 changes: 3 additions & 3 deletions id_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ func TestUnmarshalIDStruct(t *testing.T) {

func TestScan(t *testing.T) {
var id ID
value := uint64(123)
value := int64(123)

if err := id.Scan(value); err != nil {
t.Fatal(err)
Expand All @@ -109,10 +109,10 @@ func TestValue(t *testing.T) {
t.Fatal(err)
}

_, ok := driverValue.(uint64)
_, ok := driverValue.(int64)

if !ok {
t.Fatal("Driver value must be of type uint64")
t.Fatal("Driver value must be of type int64")
}
}

Expand Down

0 comments on commit e09a353

Please sign in to comment.