optional icon indicating copy to clipboard operation
optional copied to clipboard

Add pointer methods

Open mwielbut opened this issue 3 years ago • 0 comments

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 avatar Sep 02 '22 16:09 mwielbut