package main /** * Methods in Go are statically dispatched. That is, * The method executed is based on the type of the variable * at the time the method is called * * author ggtowell * created: Sep 2022 */ import "fmt" type sOne struct { intOne int floatOne float32 } func (obj sOne) String() string { return fmt.Sprintf("sOne intOne:%v floatOne:%v", obj.intOne, obj.floatOne) } type sTwo sOne func (obj sTwo) String() string { return fmt.Sprintf("sTwo intOne:%v floatOne:%v", obj.intOne, obj.floatOne) } type anInt int32 type bnInt anInt // You cannot define a method on a base type // but you can on a type from a base func (item anInt) String() string { //return fmt.Sprintf("anInt %v", item) // recursion problem -- %v wants to call the String() method return fmt.Sprintf("anInt %d", item) } func (item bnInt) String() string { //return fmt.Sprintf("bnInt %v", item) // recursion problem return fmt.Sprintf("bnInt %d", item) } func prA(item sOne) { fmt.Printf(" %v\n", item) } func main() { asOne := sOne{1, 1.61} fmt.Printf("ONE %v\n", asOne) asTwo := sTwo{2, 3.1415} // fmt.Printf("TWO %v\n", asTwo) fmt.Println("Print sOne instance from function") prA(asOne) fmt.Println("Print sTwo instance from function (explicit cast required)") prA(sOne(asTwo)) fmt.Printf("\n\n") ii := 6 ai1 := anInt(ii) fmt.Printf("ai1 %v\n", ai1) bi1 := bnInt(ai1) fmt.Printf("bi1 %v\n", bi1) }