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

omitempty not working for int/float #311

Closed
coanor opened this issue Aug 1, 2021 · 1 comment
Closed

omitempty not working for int/float #311

coanor opened this issue Aug 1, 2021 · 1 comment

Comments

@coanor
Copy link

coanor commented Aug 1, 2021

Related to #221

For tag version v0.3.1

 package main

 import (
   "bytes"
   "log"

   "github.com/BurntSushi/toml"
 )

 func demo0() {
   type X struct {
     Int int     `toml:"int,omitempty"`
     Str string  `toml:"str,omitempty"`
     F64 float64 `toml:"f64,omitempty"`
     I64  int64   `toml:"i64,omitempty"`
     U64  uint64  `toml:"u64,omitempty"`
   }

   x := X{Str: ""}

   var buf bytes.Buffer

   if err := toml.NewEncoder(&buf).Encode(x); err != nil {
     log.Fatal(err)
   }

   log.Printf("\n%s", buf.String())
 }

 func main() {
   demo0()
 }

the output is

2021/08/01 13:12:06
int = 0
f64 = 0.0
i64 = 0
u64 = 0

It seems that, the omitempty not working on int and float.

@arp242
Copy link
Collaborator

arp242 commented Aug 1, 2021

You need to use omitzero, not omitempty. The way it works:

  • omitempty – Don't write if the value is "empty": len(0) for arrays, slices, maps, strings, false for bools

  • omitzero – Don't write if the value is zero, only works for numbers.

It's annoying that it works like this, but there isn't any way to change this to the more standard behaviour without breaking comparability. It's one of the things that will be fixed in a hypothetical unplanned v2 release. See: #120.

@arp242 arp242 closed this as completed Aug 1, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants