2

[Golang] Call a Struct and its Method by Name

 2 years ago
source link: http://siongui.github.io/2016/02/11/go-call-a-struct-and-its-method-by-name/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

[Golang] Call a Struct and its Method by Name

February 11, 2016

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())
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK