[Golang merge two structs] #go #golang #merge #structs #embed
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "fmt" | |
| ) | |
| type foo struct { | |
| f int | |
| } | |
| type bar struct { | |
| b int | |
| } | |
| type baz struct { | |
| *foo | |
| *bar | |
| } | |
| type qux struct { | |
| f *foo | |
| b *bar | |
| } | |
| type combined struct { | |
| *baz | |
| } | |
| func acceptsFoo(f *foo) { | |
| fmt.Printf("accepted foo: %+v\n", f) | |
| } | |
| func acceptsAnything(f *foo, x interface{}) { | |
| fmt.Printf("f: %+v\n", f) | |
| fmt.Printf("x: %+v\n", x) | |
| } | |
| func main() { | |
| f := &foo{1} | |
| b := &bar{2} | |
| z := &baz{f, b} | |
| q := &baz{foo: f, bar: b} | |
| c := &combined{z} | |
| fmt.Printf("%+v\n", f) | |
| fmt.Printf("%+v\n", b) | |
| fmt.Printf("%+v\n", z) | |
| fmt.Printf("%+v\n", q) | |
| fmt.Printf("z.f %+v\n", z.f) | |
| fmt.Printf("z.b %+v\n", z.b) | |
| fmt.Printf("z.foo.f %+v\n", z.foo.f) | |
| fmt.Printf("z.bar.b %+v\n", z.bar.b) | |
| fmt.Printf("q.f %+v\n", q.f) | |
| fmt.Printf("q.b %+v\n", q.b) | |
| fmt.Printf("q.foo.f %+v\n", q.foo.f) | |
| fmt.Printf("q.bar.b %+v\n", q.bar.b) | |
| fmt.Printf("c.f %+v\n", c.f) | |
| fmt.Printf("c.b %+v\n", c.b) | |
| fmt.Printf("c.foo.f %+v\n", c.foo.f) | |
| fmt.Printf("c.bar.b %+v\n", c.bar.b) | |
| fmt.Printf("c.baz.foo.f %+v\n", c.baz.foo.f) | |
| fmt.Printf("c.baz.bar.b %+v\n", c.baz.bar.b) | |
| acceptsFoo(f) | |
| acceptsAnything(f, b) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment