Created
September 3, 2019 16:02
-
-
Save philipstanislaus/c6a0cc84f3bad217eadaea3e734816e8 to your computer and use it in GitHub Desktop.
Optional values with nil pointers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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