markphelps / optional

Optional is a library of optional Go types
https://godoc.org/github.com/markphelps/optional
MIT License
210 stars 19 forks source link

Add pointer methods #24

Closed mwielbut closed 1 year ago

mwielbut commented 2 years ago

This PR adds some convenience methods to make it easier to convert between pointer and Optional representation of values.

Using the Optional package inevitably leads to lots of code like this when we need to convert back to pointers:

a.FirstName.If(func(v string) {
    row.FirstName = &v
})

or the other way:

if r.FirstName != nil {
    a.FirstName = optional.NewString(*r.FirstName)
}

Two new functions are introduced, one to create an Optional given a pointer, and the other to return the embedded value as a pointer. Note, in both cases the value is copied over, the pointer is never passed directly as that would break the encapsulation.

With the two methods, the above examples become simple one-line statements:

row.FirstName = a.FirstName.ToPointer()
a.FirstName = optional.NewStringFromPointer(r.FirstName)
mwielbut commented 1 year ago

Lgtm! Thank you. Will create a new release in the morning

@markphelps any chance we could deploy today? I'd love to update our code to use this :)

markphelps commented 1 year ago

@mwielbut thanks again for the contribution!!

I just created https://github.com/markphelps/optional/releases/tag/v0.11.0 with the change

I'm going to be paying more attention to this library going forward and hope to do more regular releases. Thanks again!