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

藏色散人
Release: 2022-11-28 20:41:04
forward
5823 people have browsed it

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
}
Copy after login

Interface assertion judgment:

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

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")
Copy after login

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!

Related labels:
source:learnku.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template