package main import ( "fmt" "reflect" ) type Person struct { name string age int } func (p Person) SayHello() { fmt.Printf("Hello, my name is %s and I'm %d years old.\n", p.name, p.age) } func main() { p := Person{name: "John", age: 30} t := reflect.TypeOf(p) fmt.Println("Number of methods:", t.NumMethod()) }
Number of methods: 1
package main import ( "fmt" "reflect" ) type A struct { name string } func (a *A) SetName(name string) { a.name = name } type B struct { A } func main() { b := B{A{name: "John"}} t := reflect.TypeOf(b) fmt.Println("Number of methods:", t.NumMethod()) }
Number of methods: 1In this example, we defined two struct types `A` and `B`, where `B` embeds `A`. We also defined a method `SetName` on type `A`. We create an instance of type `B` and retrieve its type using `reflect.TypeOf`. We then call `NumMethod` on that type to get the number of methods associated with it, which in this case is 1. The `SetName` method of `A` is also considered as a method of type `B`.