pelletier / go-toml

Go library for the TOML file format
https://github.com/pelletier/go-toml
Other
1.72k stars 209 forks source link

omitempty returns nil for defined empty sections #878

Closed dbarrosop closed 1 year ago

dbarrosop commented 1 year ago

Describe the bug

When parsing a document into a struct using pointers and omitempty, empty sections are interpreted as nil same as if they weren't defined at all.

The main issue with this behavior is that the action Marshal(Unmarshal(doc)) mutates the document.

To Reproduce

Run the following example:

package main

import (
    "fmt"

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

type A struct {
    Nullable *struct {
        A string
    } `toml:"nullable,omitempty"`
}

type Doc struct {
    A *A `toml:"a,omitempty"`
}

func main() {
    doc1 := []byte(`[a]
[a.nullable]
`)
    doc2 := []byte(`[a]`)

    var d1 Doc
    if err := toml.Unmarshal(doc1, &d1); err != nil {
        panic(err)
    }
    fmt.Println(d1.A.Nullable)

    var d2 Doc
    if err := toml.Unmarshal(doc2, &d2); err != nil {
        panic(err)
    }
    fmt.Println(d2.A)
}

which prints:

<nil>
<nil>

Expected behavior

I'd expect it to return &Nullable{} in the first case as the section was defined.

Versions

Additional context