简体   繁体   English

为什么 MethodByName().Call() 返回“[<float64 Value> ]”?

[英]Why does MethodByName().Call() return "[<float64 Value>]"?

I have the following interface我有以下界面

import (
    "fmt"
    "reflect"
)

type geometry interface {
    Area() float64
    Perimeter() float64
}

func prettyPrint(geometry geometry) {
    geometryType := reflect.TypeOf(geometry)
    fmt.Println(geometryType.Name())
    fmt.Printf("\t%+v\n", geometry)

    for i := 0; i < geometryType.NumMethod(); i++ {
        method := geometryType.Method(i)
        fmt.Println(method.Name)
        fmt.Println(reflect.ValueOf(geometry).MethodByName(method.Name).Call(nil))
    }
}

When calling prettyPrint using a type which implements geometry :当使用实现geometry的类型调用prettyPrint

func main() {
    circle := circle{radius: 5}
    prettyPrint(circle)
}

This is the output这是输出

circle
        {radius:5}
Area
[<float64 Value>]
Perimeter
[<float64 Value>]

I don't quite understand the reflect.Call() method, or why its printing out each value as [<float64 Value>] - I am trying to get the resulting output from calling the func on the passed in geometry type我不太明白reflect.Call()方法,或者为什么它将每个值打印为[<float64 Value>] - 我试图通过在传入的geometry类型上调用 func 来获取结果输出

I've tried passing in []reflect.Value{} instead of nil as suggested in various places online, but it gives the same results as above我试过传入[]reflect.Value{}而不是nil正如网上各个地方所建议的那样,但它给出了与上面相同的结果

Can anyone shed some light on what exactly is going on here?任何人都可以对这里发生的事情有所了解吗?


I also tried this Invoke method from elsewhere on SO我也从其他地方尝试过这个Invoke方法

func Invoke(any interface{}, name string, args ...interface{}) {
    inputs := make([]reflect.Value, len(args))
    for i, _ := range args {
        inputs[i] = reflect.ValueOf(args[i])
    }
    fmt.Println(reflect.ValueOf(any).MethodByName(name).Call(inputs))
}

It gives the same results..它给出了相同的结果..

Invoke(circle{}, "Area")

outputs产出

[<float64 Value>]

The .Call returns a slice of values, returned by the method called. .Call 返回一个值切片,由调用的方法返回。 Both of your methods on that interface return a float64, so this is exactly what you see in the print - a slice containing a single float64 value.该接口上的两个方法都返回一个 float64,所以这正是您在打印中看到的 - 一个包含单个 float64 值的切片。 This is due to the fact the the method can be returning more than a single value.这是因为该方法可以返回多个值。

Try doing尝试做

fmt.Println(reflect.ValueOf(geometry).MethodByName(method.Name).Call(nil)[0])

and everything will start to make sense.一切都会开始变得有意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM