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

encoding/json: Embedded structs and embedded interfaces treated differently when marshaling #54322

Closed
CreatureDev opened this issue Aug 7, 2022 · 1 comment

Comments

@CreatureDev
Copy link

CreatureDev commented Aug 7, 2022

What version of Go are you using (go version)?

1.19

Does this issue reproduce with the latest release?

yes

What operating system and processor architecture are you using (go env)?

go play environment

What did you do?

import (
	"encoding/json"
	"fmt"
)

type Bar interface {
	IsBar()
}

type Barred struct {
	Str string
}

func (Barred) IsBar() {

}

type Foo1 struct {
	Bar
	I int
}

type Foo2 struct {
	Barred
	I int
}

func main() {
	var b Barred = Barred{Str: "abc"}
	var f1 Foo1 = Foo1{Bar: b, I: 123}
	var f2 Foo2 = Foo2{Barred: b, I: 123}
	e1, _ := json.Marshal(f1)
	e2, _ := json.Marshal(f2)
	if string(e1) != string(e2) {
		fmt.Println("Interface and Structure marshalled differently")
	}
}

What did you expect to see?

strings e1 and e2 to be equivalent

What did you see instead?

string e1 contained an nested structure labelled Bar instead of embedding the values into the base struct Foo1

@seankhliao
Copy link
Member

From the docs:

An anonymous struct field of interface type is treated the same as having that type as its name, rather than being anonymous.

Closing as working as documented, ref #8386

@seankhliao seankhliao closed this as not planned Won't fix, can't repro, duplicate, stale Aug 7, 2022
@golang golang locked and limited conversation to collaborators Aug 7, 2023
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

3 participants