在Go结构中获取reflect.Ptr类型到字段
I am trying to pass to a third-party package a variadic list of pointers to fields in a struct. The package accepts a variadic interface{} list ( func Persist(...interface) error ), where each of the interface values is a pointer to a variable. I created a function that mocks how the third-party library and prints out the Type and Kind of the pointers (called mockFunction below).
When I pass it the address of the struct variables in a non-variadic way, they have their primitive Types and Values within the mocked function using the reflect calls. However, when I pass them in a variadic way using expansion, they have Type: Type: reflect.Value and Kind: struct. The third-party package does not know how to handle them in this form.
I would like to figure out a way to call the third-party package with a slice of interface{} (e.g. inv := make([]interface{}, 3) and u variadic expansion on the call ) if at all possible.
Here is the code with a link to Go Playground below:
package main
import (
"fmt"
"reflect"
)
type Investment struct {
Price float64
Symbol string
极而言之
Rating int64
}
func main() {
inv := Investment{Price: 534.432, Symbol: "GBG", Rating: 4}
抗皱的方法
s := reflect.ValueOf(&inv).Elem()
描写城市繁华景象的句子
variableParms := make([]interface{}, s.NumField())
for i := 0; i < s.NumField(); i++ {
variableParms[i] = s.Field(i).Addr()
}
// non-variadic call
巴厘岛恋人mockFunction(&inv.Price, &inv.Symbol, &inv.Rating)
//variadic call
)
}
func mockFunction(values ...interface{}) {
for i, value := range values {
我和林老师的yin荡生活
弟弟结婚祝福语rv := reflect.ValueOf(value)
fmt.Printf("value %d has Type: %s and Kind %s
", i, rv.Type(), rv.Kind())
苔菜包子}
}
When I run it with the non-variadic parameters, the call to mockFunction returns the native Types and Kinds and the third-party package process them fine:
value 0 has Type: *float64 and Kind ptr
value 1 has Type: *string and Kind ptr
value 2 has Type: *int64 and Kind ptr
When I run it with the variadic parameters, the values are different and the third-party package does not know how to handle the types:
value 0 has Type: reflect.Value and Kind struct
value 1 has Type: reflect.Value and Kind struct关于宽容的作文
value 2 has Type: reflect.Value and Kind struct
Is there any way to structure the slice definition and the call to what is placed in to the slice so that it can be variadic expanded and look like passing the pointers to the struct fields in the non-variadic way?