Skip to content

Custom IsZero() method on type is ignored when using omitzero tag #1003

@singh-inder

Description

@singh-inder

Describe the bug
When using the omitzero struct tag, the current implementation calls reflect.Value.IsZero
to determine whether a value should be omitted. However, this ignores user-defined IsZero() method that some types implement (similar to how encoding/json checks for them).

go-toml/marshaler.go

Lines 390 to 392 in a0e8464

func shouldOmitZero(options valueOptions, v reflect.Value) bool {
return options.omitzero && v.IsZero()
}

To Reproduce

package main

import (
	"fmt"
	"log"

	"github.com/pelletier/go-toml/v2"
)

type Custom struct {
	Value int
}

func (c Custom) IsZero() bool {
	return c.Value < 10
}

type Example struct {
	Field Custom `toml:",omitzero"`
}

func main() {
	data := Example{Field: Custom{Value: 5}}

	d, err := toml.Marshal(data)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("%s\n", string(d))
}

Expected behavior
Field should be omitted because Custom.IsZero() returns true.

Versions

  • go-toml: a0e8464
  • go: version 1.24.6
  • operating system: Windows, Linux

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions