[Golang] Call Struct Method With Multiple Arguments And Returns by Name


Call a function (method), with multiple arguments and returns, of a struct by name during run-time in Golang. (run-time reflection)

This is an advanced example of [1].

Run Code on Go Playground

package main

import (
        "fmt"
        "reflect"
)

type DemoStruct struct {
        s string
        i int
        f float64
}

func (d *DemoStruct) DemoFunc(s string, i int, f float64) (string, int, float64, DemoStruct) {
        return s, i, f, *d
}

func main() {
        ds := DemoStruct{"sacca", 1, 3.14}

        // call DemoFunc() method
        fmt.Println(ds.DemoFunc("dukkha", 0, 1.414))

        // call DemoFunc() method by Name
        retv := reflect.ValueOf(&ds).MethodByName("DemoFunc").Call([]reflect.Value{
                reflect.ValueOf("dukkha"),
                reflect.ValueOf(13),
                reflect.ValueOf(1.414),
        })
        fmt.Println(retv[0].String())
        fmt.Println(retv[0].Interface().(string))
        fmt.Println(retv[1].Int())
        fmt.Println(retv[1].Interface().(int))
        fmt.Println(retv[2].Float())
        fmt.Println(retv[2].Interface().(float64))
        fmt.Println(retv[3].Interface().(DemoStruct))
}

References:

[1][Golang] Call a Struct and its Method by Name
[2]golang reflect method example
[3]Call a Struct and its Method by name in Go? - Stack Overflow
[4]golang reflect example
[5]python reflection class name
[6]introspection - Getting the class name of an instance in Python - Stack Overflow
[7]reflect - The Go Programming Language
[8]The Laws of Reflection - The Go Blog
[9]谈一谈Go的interface和reflect | legendtkl
[10]为什么golang不能通过字符串来创建对象实例? - Go 语言 - 知乎
[11]Go 反射实践及剖析 - 文章 - 伯乐在线
[12]Could anyone help me with some reflection voodoo please? : golang
[13]
[14]
[15]Advent 2018: The Relationship Between Interfaces and Reflection : golang