Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save philipstanislaus/506d7ed40f5424caeb3f861786f0803c to your computer and use it in GitHub Desktop.
Save philipstanislaus/506d7ed40f5424caeb3f861786f0803c to your computer and use it in GitHub Desktop.
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