Skip to content
Related Articles

Related Articles

reflect.NumMethod() Function in Golang with Examples
  • Last Updated : 05 May, 2020

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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)
    }
}

chevron_right


Output:

Geek1
Geek2

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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)
    }
}

chevron_right


Output:

2009/11/10 23:00:00 Land
2009/11/10 23:00:00 TakeOff
2009/11/10 23:00:00 ToggleNose
My Personal Notes arrow_drop_up
Recommended Articles
Page :