moneyzmey
moneyzmey

Reputation: 155

Reflect (MethodByName) not valid

Problem at reflection, with MethodByName

Code:

package main

import (
    "reflect"
    "fmt"
)

type test struct {}

var serviceType = map[string]reflect.Value{
    "test": reflect.ValueOf(test{}),
}

func (t *test) prnt()  {
    fmt.Println("test ok")
}

func callFunc(strct string, fName string)  {

    s := serviceType[strct].MethodByName(fName)
    if !s.IsValid(){
        fmt.Println("not correct")
        return
    }

    s.Call(make([]reflect.Value,0))
}

func main()  {
    callFunc("test", "prnt")
}

Output:

not correct

Playground: https://play.golang.org/p/ZLEQBGYoUOB

Could you help, what I'm doing wrong ?

Upvotes: 2

Views: 1125

Answers (1)

Anuruddha
Anuruddha

Reputation: 3245

Two things needs to be corrected.

  1. MethodByName() returns only Exported methods. So you have to rename prnt tp Prnt
  2. Needs to pass a pointer of struct test to reflect.ValueOf() method.

Here is the modified working code https://play.golang.org/p/4MK2kqOz6e2

Upvotes: 7

Related Questions