Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Optional values with empty field
package playground_optional_values_with_nil_pointers
import (
"fmt"
"testing"
"github.com/ChainSafe/gossamer/codec"
)
// Bool represents boolean values
type Bool struct {
Value bool
Empty bool
}
// NewBool creates a new Bool
func NewBool(v bool) Bool {
return Bool{v, false}
}
func NewEmptyBool() Bool {
return Bool{false, true}
}
func (b *Bool) Encode() ([]byte, error) {
return codec.Encode(b.Value)
}
func (b *Bool) String() string {
if b.Empty {
return fmt.Sprintf("nil")
}
return fmt.Sprintf("%t", b.Value)
}
func (b *Bool) Get() (empty bool, value bool) {
return b.Empty, b.Value
}
func (b *Bool) Set(v bool) {
b.Value = v
b.Empty = false
}
func (b *Bool) SetEmpty() {
b.Value = false
b.Empty = true
}
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.