Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Optional values with nil pointers
package playground_optional_values_with_nil_pointers
import (
"fmt"
"testing"
"github.com/ChainSafe/gossamer/codec"
)
// Bool represents boolean values
type Bool struct {
Value *bool
}
// NewBool creates a new Bool
func NewBool(b bool) Bool {
return Bool{&b}
}
func NewEmptyBool() Bool {
return Bool{nil}
}
func (b *Bool) IsEmpty() bool {
return b.Value == nil
}
func (b *Bool) Encode() ([]byte, error) {
return codec.Encode(b.Value)
}
func (b *Bool) String() string {
empty, value := b.Get()
if empty {
return fmt.Sprintf("nil")
}
return fmt.Sprintf("%t", value)
}
func (b *Bool) Get() (empty bool, value bool) {
if b.Value == nil {
return true, false
}
return false, *b.Value
}
func (b *Bool) Set(i bool) {
b.Value = &i
}
func (b *Bool) SetEmpty() {
b.Value = nil
}
func TestNo3(t *testing.T) {
b := NewBool(true)
c := NewEmptyBool()
fmt.Println(b.String())
fmt.Println(c.String())
b.SetEmpty()
c.Set(false)
fmt.Println(b.String())
fmt.Println(c.String())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.