使用MethodByName如何检查实际函数是否存在?

huangapple go评论220阅读模式
英文:

How to check if the actual function exists using MethodByName?

问题

我正在使用反射作为一个快速且简单的脚本处理程序,但是我无法弄清楚错误检查的方法。

如何检查MethodByName是否找到了有效的方法?

文档中说的是零值-什么是零值?

有人能帮忙吗?

以下是代码的翻译部分:

  1. type step struct {
  2. Action string
  3. Parameter string
  4. Second string
  5. }
  6. func doStep(little step) (err error) {
  7. apiR := reflect.ValueOf(skript{})
  8. apiF := apiR.MethodByName(little.Action)
  9. if apiF == reflect.Zero(reflect.TypeOf(skript.Approve)) {
  10. return errors.New("xxx")
  11. }
  12. args := []reflect.Value{reflect.ValueOf(little.Parameter), reflect.ValueOf(little.Second)}
  13. apiF.Call(args)
  14. return nil
  15. }
  16. type skript struct{}
  17. func (skript) Approve(who string, dummy string) {
  18. fmt.Println("Approve ", who, dummy)
  19. }
  20. func main() {
  21. st1 := step{"Approve", "me", "ok"}
  22. st2 := step{"Block", "me", "ok"}
  23. doStep(st1)
  24. doStep(st2)
  25. }

请注意,我只翻译了代码部分,不包括问题本身。

英文:

I am using reflection as a quick & dirty script handler but I can't figure out the error checking

How do I check that MethodByName has found a valid method?

Docs say zero value - what zero value?

anybody able to help?

https://play.golang.org/p/ogypx-wLay

  1. type step struct {
  2. Action string
  3. Parameter string
  4. Second string
  5. }
  6. func doStep(little step) (err error) {
  7. apiR := reflect.ValueOf(skript{})
  8. apiF := apiR.MethodByName(little.Action)
  9. if apiF == reflect.Zero(reflect.TypeOf(skript.Approve)) {
  10. return errors.New("xxx")
  11. }
  12. args := []reflect.Value{reflect.ValueOf(little.Parameter), reflect.ValueOf(little.Second)}
  13. apiF.Call(args)
  14. return nil
  15. }
  16. type skript struct{}
  17. func (skript) Approve(who string, dummy string) {
  18. fmt.Println("Approve ", who, dummy)
  19. }
  20. func main() {
  21. st1 := step{"Approve", "me", "ok"}
  22. st2 := step{"Block", "me", "ok"}
  23. doStep(st1)
  24. doStep(st2)
  25. }

答案1

得分: 4

根据标准文档:

> zero Value 表示没有值。它的 IsValid 方法返回 false,它的 Kind 方法返回 Invalid,它的 String 方法返回 ""

所以你想在从 MethodByName 返回的值上使用 IsValid 方法。如果它返回 false,表示出现了错误。

英文:

From standard docs:

> The zero Value represents no value. Its IsValid method returns false, its Kind method returns Invalid, its String method returns "<invalid Value>"

So you want to use the IsValid method on the returned value from MethodByName. If it's false there was an error.

huangapple
  • 本文由 发表于 2017年5月17日 04:16:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/44010827.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定