Created
September 3, 2019 16:03
-
-
Save philipstanislaus/506d7ed40f5424caeb3f861786f0803c to your computer and use it in GitHub Desktop.
Optional values with empty field
This file contains hidden or 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 | |
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