/* * methods in Go are dispatched statically. * NOT inherited. * If you define a struct as anonymous include of * another struct, methods are inherited. * Non-anonymous == methods are not inherited * I never remember all of this! * * @author gtowell * created: Aug 6, 2021 */ package main import "fmt" // simple struct type SNum struct { num int } // simple method on struct func (s SNum) printer() { fmt.Printf("SNum num=%d\n", s.num) } // a new type that is just a renaming of the original struct type SSNum SNum // new method on the renaming func (s SSNum) printer() { fmt.Printf("SSNum num=%d\n", s.num) } // struct with anonymous include type SNumAndStr struct { SNum str string } // similar struct but with named include. type S2 struct { sn SNum str string } func main() { sn := SNum{num:5} sn.printer() // cast SNum to SSNum ssn:= SSNum(sn) // the printer method used is from SSNUM // In Java it would be from SNum ssn.printer() // with anonymous include the methods on included struct are available nands := SNumAndStr{SNum{num:7}, "test"} fmt.Println(nands) nands.printer() // with named include, methods are NOT available. s2 := S2{SNum{9}, "hello"} fmt.Println(s2) //s2.printer() }