Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support IsZeroers when checking for isZero #353

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions encode.go
Original file line number Diff line number Diff line change
Expand Up @@ -612,7 +612,14 @@ func getOptions(tag reflect.StructTag) tagOptions {
return opts
}

type isZeroer interface {
IsZero() bool
}

func isZero(rv reflect.Value) bool {
if z, ok := rv.Interface().(isZeroer); ok {
return z.IsZero()
}
switch rv.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return rv.Int() == 0
Expand Down
16 changes: 16 additions & 0 deletions encode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,22 @@ unsigned = 5
encodeExpected(t, "simple with omitzero, non-zero", value, expected, nil)
}

func TestEncodeWithOmitZeroWithIsZeroer(t *testing.T) {
type simple struct {
Time time.Time `toml:"time,omitzero"`
}

value := simple{time.Time{}}
expected := ""

encodeExpected(t, "simple with omitzero, iszeroer, zero", value, expected, nil)

value.Time = time.Date(2006, time.January, 2, 15, 4, 5, 0, time.UTC)
expected = `time = 2006-01-02T15:04:05Z
`
encodeExpected(t, "simple with omitzero, iszeroer, non-zero", value, expected, nil)
}

func TestEncodeOmitemptyWithEmptyName(t *testing.T) {
type simple struct {
S []int `toml:",omitempty"`
Expand Down