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

Slices of structs are not properly reset when unmarshalling #931

Closed
kkoreilly opened this issue Feb 8, 2024 · 3 comments · Fixed by #934
Closed

Slices of structs are not properly reset when unmarshalling #931

kkoreilly opened this issue Feb 8, 2024 · 3 comments · Fixed by #934
Labels
bug Issues describing a bug in go-toml.

Comments

@kkoreilly
Copy link

Describe the bug
When unmarshalling a slice of structs (array of tables in TOML terminology) into a Go slice, any elements already present in the slice are not reset, leading to compounding slices. This did not happen in v1.

To Reproduce

main.go:

package main

import (
	"fmt"
	"os"

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

type item struct {
	Name string
}

type items struct {
	Slice []item
}

func main() {
	its := items{[]item{{"a"}, {"b"}}}
	b, _ := os.ReadFile("slice.toml")
	toml.Unmarshal(b, &its)
	fmt.Println(its) // should be {[{c} {d}]}, but get {[{a} {b} {c} {d}]}
}

slice.toml:

[[Slice]]
  Name = 'c'

[[Slice]]
  Name = 'd'

Expected behavior
As stated in the code, I expected {[{c} {d}]} but got {[{a} {b} {c} {d}]}.

Versions

  • go-toml: v2.1.1 (34765b4)
  • go: 1.21.4
  • operating system: Windows and macOS

Additional context
As stated above, I have confirmed that this issue did not happen in v1.

@pelletier
Copy link
Owner

Good catch, thank you for the bug report!

The intent is to match encoding/json's behavior when unmarshaling. I've confirmed (https://go.dev/play/p/WQ8VPf5C-L1) it resets the slice and the resulting value is {[{c} {d}]}.

pelletier added a commit that referenced this issue Feb 27, 2024
When decoding into a non-empty slice, it needs to be emptied so that only the
tables contained in the document are present in the resulting value.

Arrays are not impacted because their unmarshal offset is tracked separately.

Fixes #931
pelletier added a commit that referenced this issue Feb 27, 2024
When decoding into a non-empty slice, it needs to be emptied so that only the
tables contained in the document are present in the resulting value.

Arrays are not impacted because their unmarshal offset is tracked separately.

Fixes #931
@pelletier
Copy link
Owner

@kkoreilly I've merged #934, which should address your issue. Let me know if it worked, feel free to re-open this issue if not!

@kkoreilly
Copy link
Author

It worked, thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Issues describing a bug in go-toml.
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants