Radar · Go · Archive · Week 28 · Jul 7 – 13, 2025
encoding/xml: add omitzero option
Worth knowingstdlib
- What changed
- The
encoding/xmlpackage now supports anomitzerostruct tag option. When marshaling, a field withomitzerois omitted if its value is zero as determined byIsZero()if present, otherwise byreflect.Value.IsZero. The option is ignored during unmarshaling and combines withomitemptyusing logical OR. - Production impact
- The source does not say.
- Try it
- Marshal a struct with a field tagged
xml:"name,omitempty,omitzero"and observe when the field is omitted. - Source
- github.com/golang/go/issues/69857
Understand it, then run it
Run it now
// This program demonstrates the new omitzero option in encoding/xml.
// It shows that a field with omitzero is omitted when its value is zero.
// The program runs under Go 1.27.1, which already includes the change.
package main
import (
"encoding/xml"
"fmt"
)
type Example struct {
// The omitzero tag causes this field to be omitted when empty.
Name string `xml:"Name,omitempty,omitzero"`
// A slice that is nil will be omitted, but a zero-length slice will be emitted.
Items []int `xml:"Item,omitempty,omitzero"`
}
func main() {
// Create a value with zero fields.
e := Example{}
// Marshal to XML.
data, err := xml.MarshalIndent(e, "", " ")
if err != nil {
panic(err)
}
// Print the resulting XML. The Name element is omitted because it is zero.
// The Items element is omitted because the slice is nil.
fmt.Println(string(data))
}
What it printed when we ran it on Go 1.27.1
<Example></Example>
Run sends this program (for Solidity, the contract and its tests) to our own sandbox, where it is compiled and run once, with no network, and what it printed or the test report comes back here. Nothing is kept. Runs are counted per visitor for the day so everyone gets a turn; the details are on the legal page.
Written by gpt-oss-20b from the linked source · claims checked against the sources · archive, not individually reviewed