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

青灯夜游
Release: 2023-02-21 19:44:16
forward
4364 people have browsed it

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

[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!

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