Open In App

reflect.NumMethod() Function in Golang with Examples

Last Updated : 05 May, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package. The reflect.NumMethod() Function in Golang is used to get the number of exported methods in the value’s method set. To access this function, one needs to imports the reflect package in the program.

Syntax:

func (v Value) NumMethod() int

Parameters: This function does not accept any parameter.

Return Value: This function returns the number of exported methods in the value’s method set.

Below examples illustrate the use of the above method in Golang:

Example 1:




// Golang program to illustrate
// reflect.NumMethod() Function 
   
package main
   
import (
    "fmt"
    "reflect"
)
   
type gfg struct {
    Prop string
}
  
func (f gfg) Geek1() string {
    return f.Prop
}
  
func (f gfg) Geek2() {
}
  
// Main function 
func main() {
    fooType := reflect.TypeOf(gfg{})
    for i := 0; i < fooType.NumMethod(); i++ {
        method := fooType.Method(i)
        fmt.Println(method.Name)
    }
}


Output:

Geek1
Geek2

Example 2:




// Golang program to illustrate
// reflect.NumMethod() Function 
   
package main
   
import (
    "log"
    "reflect"
)
   
type Reindeer string
  
func (r Reindeer) TakeOff() {
    log.Printf("%q lifts off.", r)
}
  
func (r Reindeer) Land() {
    log.Printf("%q gently lands.", r)
}
  
func (r Reindeer) ToggleNose() {
    if r != "rudolph" {
        panic("invalid reindeer operation")
    }
    log.Printf("%q nose changes state.", r)
}
  
func main() {
    r := Reindeer("rudolph")
  
    t := reflect.TypeOf(r)
  
    for i := 0; i < t.NumMethod(); i++ {
        m := t.Method(i)
        log.Printf("%s", m.Name)
    }
}


Output:

2009/11/10 23:00:00 Land
2009/11/10 23:00:00 TakeOff
2009/11/10 23:00:00 ToggleNose


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads