Home >Backend Development >Golang >How does Go language determine whether a certain method exists in a structure? Two ways to introduce

How does Go language determine whether a certain method exists in a structure? Two ways to introduce

青灯夜游
青灯夜游forward
2023-02-14 19:32:304353browse

How to determine whether a method exists in a structure in Go language? The following article will introduce to you two ways in Golang to determine whether a certain method exists in a structure (with code examples). I hope it will be helpful to you!

How does Go language determine whether a certain method exists in a structure? Two ways to introduce

go Sometimes you need to judge whether a certain structure has a certain method, but you may suddenly feel confused. Go can also judge like PHP

Yes, although go does not provide a ready-made method, existing logic can be used to encapsulate the implementation.

There are currently two methods available. One is to know the complete method and can use interface assertion to judge. The second is to use reflection to complete the 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")

[Recommended learning: go视频 tutorial

The above is the detailed content of How does Go language determine whether a certain method exists in a structure? Two ways to introduce. 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