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
Release: 2024-12-24 05:30:14
Original
944 people have browsed it

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

Output:

My statement
Copy after login

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!

source:php.cn
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template