From 01e551605fc3abcd36d72d98c81971d431835d54 Mon Sep 17 00:00:00 2001 From: Martin Tournoij Date: Sat, 12 Feb 2022 16:49:34 +0100 Subject: [PATCH] Skip fields with toml:"-", even when they're unsupported types Previously something like this would fail to encode due to func being an unsupported type: struct { Str string `toml:"str" Func func() `toml:"-"` } But that's not really needed in this case, since we will never encode it anyway. Fixes #345 --- encode.go | 4 ++++ encode_test.go | 27 +++++++++++++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/encode.go b/encode.go index dee4e6d3..860359c7 100644 --- a/encode.go +++ b/encode.go @@ -398,6 +398,10 @@ func (enc *Encoder) eStruct(key Key, rv reflect.Value, inline bool) { if f.PkgPath != "" && !f.Anonymous { /// Skip unexported fields. continue } + opts := getOptions(f.Tag) + if opts.skip { + continue + } frv := rv.Field(i) diff --git a/encode_test.go b/encode_test.go index f12cd9c7..69f1c533 100644 --- a/encode_test.go +++ b/encode_test.go @@ -468,6 +468,33 @@ func TestEncode32bit(t *testing.T) { nil) } +// Skip invalid types if it has toml:"-" +// +// https://github.com/BurntSushi/toml/issues/345 +func TestEncodeSkipInvalidType(t *testing.T) { + buf := new(bytes.Buffer) + err := NewEncoder(buf).Encode(struct { + Str string `toml:"str"` + Arr []func() `toml:"-"` + Map map[string]interface{} `toml:"-"` + Func func() `toml:"-"` + }{ + Str: "a", + Arr: []func(){func() {}}, + Map: map[string]interface{}{"f": func() {}}, + Func: func() {}, + }) + if err != nil { + t.Fatal(err) + } + + have := buf.String() + want := "str = \"a\"\n" + if have != want { + t.Errorf("\nwant: %q\nhave: %q\n", want, have) + } +} + func encodeExpected(t *testing.T, label string, val interface{}, want string, wantErr error) { t.Helper()