Call a Struct and its Method by name in Go?


I have found a function call MethodByName() here but it’s not exactly what I want! (maybe because I don’t know how to use it … I cannot find any example with it). What I want is:

type MyStruct struct {
//some feilds here
func (p *MyStruct) MyMethod { 
    println("My statement."); 

CallFunc("MyStruct", "MyMethod"); 
//print out "My statement." 

So I guess, first I need something like StructByName() and after that use it for MethodByName(), is that right!?


To call a method on an object, first use reflect.ValueOf. Then find the method by name, and then finally call the found method. For example:

package main

import "fmt"
import "reflect"

type T struct {}

func (t *T) Foo() {

func main() {
    var t T

Answered By – user811773

Answer Checked By – Candace Johnson (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.