https://github.com/elgopher/ptr
Generic Go functions to get optional values
https://github.com/elgopher/ptr
generic generics go golang option optional
Last synced: 5 days ago
JSON representation
Generic Go functions to get optional values
- Host: GitHub
- URL: https://github.com/elgopher/ptr
- Owner: elgopher
- License: mit
- Created: 2023-02-25T11:14:35.000Z (over 3 years ago)
- Default Branch: master
- Last Pushed: 2023-02-26T10:36:37.000Z (over 3 years ago)
- Last Synced: 2026-04-25T19:32:32.444Z (about 1 month ago)
- Topics: generic, generics, go, golang, option, optional
- Language: Go
- Homepage:
- Size: 13.7 KB
- Stars: 2
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# ptr
Generic functions to get optional values
[](https://pkg.go.dev/github.com/elgopher/ptr)
[](https://codecov.io/gh/elgopher/ptr)
[](https://www.repostatus.org/#active)
## Problems with Go optional values
By convention, optional values in Go are pointers:
```go
type Input struct {
RequiredField string
OptionalField *string
}
```
But such structs **cannot** be initialized in a single expression:
```go
in := Input{
RequiredField: "works",
OptionalField: &("does not work"),
}
```
And accessing optional fields makes code look ugly:
```go
if in.OptionalField != nil && *in.OptionalField == "value" {
...
}
```
Sometimes even unsafe:
```go
value := "v1"
in.OptionalField = &value
value = "v2" // ups... in.OptionalField is changed too!
```
## This tiny packages simplifies the use of optional values
One-line initialization:
```go
import "github.com/elgopher/ptr"
in := Input{
RequiredField: "works",
OptionalField: ptr.To("this also works"),
}
```
Getting values without boilerplate code:
```go
if ptr.Value(in.OptionalField) == "value" {
// if in.OptionalField is nil then zero value is returned ("" for string)
...
}
```
or get value by specifying the default value when in.OptionalField is nil:
```go
v := ptr.ValueOrDefault(in.OptionalField, "defaultValue")
```
Safe code:
```go
value := "v1"
in.OptionalField = ptr.To(value)
value = "v2" // in.OptionalField is not changed
```
or
```go
newPointer := ptr.Copy(in.OptionalField)
```
## Installation
```shell
go get github.com/elgopher/ptr@latest
```