Skip to content

How can I use []string and []someStruct at the same field? #974

@assisken

Description

@assisken

Describe the bug
I wanna use []string or []someStruct as the same field to hide some complex fields from users when they not need them.
How can I make described behaviour like in example below?

To Reproduce
Example toml file

foo = ["a", "b"]
# the same as
foo = [{name = "a", value = "a"}, {name = "b", value = "b"}]
type config struct {
	Foo []fooConfig `toml:"foo"`
}

type fooConfig struct {
	Name  string `toml:"name"`
	Value string `toml:"value"`
}

func (c *fooConfig) UnmarshalText(b []byte) error {
	data := string(b)
	if data == "" { return nil } // passes when table

	c.Name = data
	c.Value = data

	return nil
}

func main() {
	var foo config

	data := []byte(`foo = ["a", "b", "c"]`)
	if toml.Unmarshal(data, &foo) != nil { log.Fatal() }
	fmt.Println(foo)  // as expected: {[{a a} {b b} {c c}]}

	data = []byte(`foo = [{name = "a", value = "a"}, {name = "b", value = "b"}]`)
	if toml.Unmarshal(data, &foo) != nil { log.Fatal() }
	fmt.Println(foo)  // just default values: {[{ } { }]}
}

Expected behavior

  • For foo = ["a", "b"] out put must be {[{a a} {b b} {c c}]} (works for now)
  • For foo = [{name = "a", value = "a"}, {name = "b", value = "b"}] the same {[{a a} {b b} {c c}]} (does not work)

Versions

  • go-toml: version v2.2.3
  • go: 1.23
  • operating system: 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