Skip to content

Instantly share code, notes, and snippets.

@bojand
Last active August 24, 2018 17:36
Show Gist options
  • Save bojand/69d0918cceb8491428d37e6ec846b131 to your computer and use it in GitHub Desktop.
Save bojand/69d0918cceb8491428d37e6ec846b131 to your computer and use it in GitHub Desktop.
Go structs
package main
import (
"fmt"
)
type E struct{}
func (e *E) foo() {
fmt.Println("E.foo()")
e.bar()
}
func (e *E) bar() {
fmt.Println("E.bar()")
}
type M struct {
E
}
func (e *M) bar() {
fmt.Println("M.bar()")
}
func main() {
m := M{}
m.bar()
m.foo()
}
package main
import (
"fmt"
)
type A struct {
foo string
}
func (this *A) PrintFoo() {
fmt.Println("foo: " + this.foo)
}
type B struct {
bar string
}
func (this *B) PrintBar() {
fmt.Println("bar: " + this.bar)
}
type C struct {
A
B
}
type D struct {
*A
*B
}
func PrintA(a *A) {
fmt.Println("PrintA")
a.PrintFoo()
fmt.Println("------")
}
func PrintB(b *B) {
fmt.Println("PrintB")
b.PrintBar()
fmt.Println("------")
}
func PrintC(c *C) {
fmt.Println("PrintC")
c.PrintFoo()
c.PrintBar()
fmt.Println("------")
}
func main() {
a := A{foo: "fooA"}
a.PrintFoo()
b := B{bar: "barB"}
b.PrintBar()
c := C{A{foo: "fooC"}, B{bar: "barC"}}
fmt.Printf("%+v\n", c)
fmt.Printf("%+v\n%+v\n", c.foo, c.bar)
c.PrintFoo()
c.PrintBar()
fmt.Println("")
PrintA(&a)
PrintA(&c.A)
PrintB(&b)
PrintB(&c.B)
PrintC(&c)
c2 := C{a, b}
PrintC(&c2)
fmt.Printf("%T: &a=%p a=%+v\n", a, &a, a)
fmt.Printf("%T: &b=%p b=%+v\n", b, &b, b)
fmt.Printf("%T: &c=%p c=%+v\n", c, &c, c)
fmt.Printf("%T: &c.A=%p c.A=%+v\n", c.A, &c.A, c.A)
fmt.Printf("%T: &c2.A=%p c2.A=%+v\n", c2.A, &c2.A, c2.A)
c2.A.foo = "changed c2.A.foo"
fmt.Printf("%T: &a=%p a=%+v\n", a, &a, a)
fmt.Printf("%T: &c2.A=%p c2.A=%+v\n", c2.A, &c2.A, c2.A)
fmt.Println("D: ----")
d := D{&a, &b}
fmt.Printf("%T: &a=%p a=%+v\n", a, &a, a)
fmt.Printf("%T: &d=%p d=%+v\n", d, &d, d)
fmt.Printf("%T: &d.A=%p d.A=%+v\n", d.A, &d.A, d.A)
d.A.foo = "changed d.A.foo"
fmt.Printf("%T: &a=%p a=%+v\n", a, &a, a)
fmt.Printf("%T: &d=%p d=%+v\n", d, &d, d)
fmt.Printf("%T: &d.A=%p d.A=%+v\n", d.A, &d.A, d.A)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment