Home >Backend Development >Golang >How Can I Call a Go Struct Method by Its Name Using Reflection?

How Can I Call a Go Struct Method by Its Name Using Reflection?

Linda Hamilton
Linda HamiltonOriginal
2024-12-24 05:30:14952browse

How Can I Call a Go Struct Method by Its Name Using Reflection?

Invoking Struct Methods by Name in Go

The query pertains to calling a method on a Go struct by specifying its name. Unlike the provided MethodByName() function, the OP envisions a more direct approach.

Implementing the Request

To accomplish this, utilize the following steps:

  1. Obtain the Struct Value: Use reflect.ValueOf to obtain the value of the struct pointer.
  2. Locate the Method by Name: Employ MethodByName() to find the desired method within the struct value.
  3. Invoke the Method: Call the discovered method using Call(), passing an empty slice of reflect.Value arguments in this case.

Example Implementation:

package main

import "fmt"
import "reflect"

type MyStruct struct {}

func (p *MyStruct) MyMethod() {
    fmt.Println("My statement")
}

func main() {
    var s MyStruct
    reflect.ValueOf(&s).MethodByName("MyMethod").Call(nil)
}

Output:

My statement

Note: The MethodByName() function accepts a string argument representing the method's name.

The above is the detailed content of How Can I Call a Go Struct Method by Its Name Using Reflection?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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