[Golang] Call a Struct and its Method by Name


Call a function (method) of a struct by name during run-time in Golang. (run-time reflection)

Run Code on Go Playground

package main

import (
        "fmt"
        "math"
        "reflect"
)

type Circle struct {
        r float64
}

func (c *Circle) Area() float64 {
        return math.Pi * c.r * c.r
}

func main() {
        c := Circle{1.2}

        // call Area() method
        fmt.Println(c.Area())

        // call Area() method by Name
        v := reflect.ValueOf(&c).MethodByName("Area").Call([]reflect.Value{})
        fmt.Println(v[0].Float())
}

References:

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