當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Golang reflect.NumMethod()用法及代碼示例

Go語言提供了運行時反射的內置支持實現,並允許程序借助反射包來操縱任意類型的對象。 Golang中的reflect.NumMethod()函數用於獲取值的方法集中導出的方法的數量。要訪問此函數,需要在程序中導入反射包。

用法:
func (v Value) NumMethod() int

參數:此函數不接受任何參數。

返回值:此函數返回值的方法集中導出的方法的數量。

以下示例說明了以上方法在Golang中的用法:



範例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) 
    } 
}

輸出:

Geek1
Geek2

範例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) 
    } 
}

輸出:

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



相關用法


注:本文由純淨天空篩選整理自SHUBHAMSINGH10大神的英文原創作品 reflect.NumMethod() Function in Golang with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。