https://github.com/trivigy/ref
Implements functions for de-referencing primitive types
https://github.com/trivigy/ref
golang optional pointers struct
Last synced: 6 months ago
JSON representation
Implements functions for de-referencing primitive types
- Host: GitHub
- URL: https://github.com/trivigy/ref
- Owner: trivigy
- License: mit
- Created: 2019-02-25T17:28:20.000Z (about 7 years ago)
- Default Branch: master
- Last Pushed: 2019-07-08T00:37:38.000Z (over 6 years ago)
- Last Synced: 2025-10-12T00:03:11.383Z (6 months ago)
- Topics: golang, optional, pointers, struct
- Language: Go
- Homepage:
- Size: 15.6 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE.md
Awesome Lists containing this project
README
# Ref
[](https://circleci.com/gh/trivigy/workflows/ref)
[](LICENSE.md)
[](http://godoc.org/github.com/trivigy/ref)
[](https://github.com/trivigy/ref/releases/latest)
## Introduction
In golang v1, unfortunately, there is no nice builtin way to represent optional
`struct` fields for primitives whose zero value is individualized for each
primitive. A lot of debating has been done and people hold different opinions
as to what is the best solution. This library is my personal preferred way
of dealing with the situation.
## Example
```go
package main
import (
"fmt"
"github.com/trivigy/ref"
)
type Sample struct {
Field *string `json:"field,omitempty"`
}
func main() {
result := Sample{
Field: ref.String("example"),
}
if result.Field != nil {
fmt.Print("'Field' is set")
}
}
```
## Alternatives
* https://www.reddit.com/r/golang/comments/1tst88/optional_field_in_a_struct_pointer_vs_nullintlike/
If you hold another opinion feel free to share it either via discord or on
golang github channels. Or better yet share a PR with a new link added above.