I'm using the go language and I'm having trouble using optional. Since it is not enough to include the library, I wrote it with reference to the following code. Reference https://github.com/markphelps/optional
NewInt(i int) optional.Int Create an optional type. Get() (int, bool) Take out the contents of optinal. Returns value true if the value exists, 0, false if not. Set(i int) Set the value to optional. Present() bool Check if there is a value.
package optional
// Int - optional int
type Int struct {
value *int
}
// NewInt - create an optional.Int from int
func NewInt(i int) Int {
return Int{value: &i}
}
// Get - get the wrapped value
func (i Int) Get() (int, bool) {
if i.Present() {
return *i.value, true
}
var zero int
return zero, false
}
// Set - set value
func (i Int) Set(j int) {
i.value = &j
}
// Present - return whether or not the value is present.
func (i Int) Present() bool {
return i.value != nil
}
It's a simple implementation, but I'm glad I could do something like optional. It is good to be able to write the state of None with optional.Int {}. If you want to decode to json or want optional in other types, you can import https://github.com/markphelps/optional.
Recommended Posts