google / google/uuid

`IsZero()` and `ToNullUUID` Helper Functions

Open
#113 3 comments 8 reactions 0 assignees View on GitHub
Dominant language
Go
Stars
6.1k
Forks
440
PR merge metrics
No merged PRs in 30d

Description

## Summary

Suggest adding a couple helper functions.

### `IsZero`

`IsZero()` allows uuid to support the `Nullable` interface and interface better with existing code. It can be as simple as:
```go
func (u UUID) IsZero() bool {
return u == Nil
}
```

This is particularly important when interfacing UUID with the existing ORM libraries. Heck, `IsZero()` is even used by the reflect package too!

### `ToNullUUID`

Another helper function that is used by [this null package](https://github.com/volatiletech/null) (and is quite convenient) are to-null values from the original primitives. So in the case of `uuid.UUID` and `uuuid.NullUUID`, adding the following helper function.

```go
func ToNullUUID[T uuid.UUID | uuid.NullUUID](id T) uuid.NullUUID {
if v, ok := any(id).(uuid.UUID); ok {
if v == uuid.Nil {
return uuid.NullUUID{}
}

return uuid.NullUUID{v, true}
} else if v, ok := any(id).(uuid.NullUUID); ok {
return v
} else {
panic("this should not happen")
}
}
```

That way we don't have to write the following code:

```go
id := uuid.New()

// If you know that id is not nil
nullVal := uuid.NullUUID{id, true}

// if you don't know whether or not id is nil.
nullVal := uuid.NullUUID{id, id == uuid.Nil}

// And if you want to use named struct fields
nullVal := uuid.NullUUID{UUID: id, Valid: id == uuid.Nil}

// What it looks like with the helper function
nullVal := uuid.ToNullUUID(id)
```

This is particularly useful when combined with existing libraries such as ORMs. Casting to `uuid.NullUUID` is common.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.