Home  >  Article  >  Backend Development  >  Two ways for Golang to determine whether a method exists in a structure (with code examples)

Two ways for Golang to determine whether a method exists in a structure (with code examples)

藏色散人
藏色散人forward
2022-11-28 16:22:165806browse

This article will teach you Golang and talk about how Golang determines whether a structure has a certain method. I hope it will be helpful to everyone.

Two ways for Golang to determine whether a method exists in a structure (with code examples)

go Determine whether a structure has a certain method

go Sometimes it is necessary to determine whether a certain structure has a certain method , but you may suddenly feel confused. Go can also determine

like PHP. Yes, although go does not provide a ready-made method, it can be encapsulated and implemented using existing logic. [Recommended learning: go video tutorial]

There are currently two methods that can be used. One is to know the complete method and can use the interface assertion method to judge, and the second is to use reflection. Complete judgment.

Prepare the structure that needs to be judged:

type  RefData  struct  {}

func  (this  *RefData)  Show(data  any,  name  string)  string  {
  data2  :=  data.(string)  +  "==="  +  name

  return  data2
}

Interface assertion judgment:

refDataExists := false
var refDataOb any = &RefData{}
if _, ok := refDataOb.(interface {
    Show(any, string) string
}); ok {
    refDataExists = true
}

Reflection judgment:

import(
  "reflect"
)
// 判断结构体方法是否存在
func MethodExists(in any, method string) bool {
    if method == "" {
        return false
    }
    p := reflect.TypeOf(in)
    if p.Kind() == reflect.Pointer {
        p = p.Elem()
    }
    // 不是结构体时
    if p.Kind() != reflect.Struct {
        return false
    }
    object := reflect.ValueOf(in)
    // 获取到方法
    newMethod := object.MethodByName(method)
    if !newMethod.IsValid() {
        return false
    }
    return true
}
// 使用
refDataExists := MethodExists(&RefData{},  "Show")

The above is the detailed content of Two ways for Golang to determine whether a method exists in a structure (with code examples). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:learnku.com. If there is any infringement, please contact admin@php.cn delete