【发布时间】:2017-08-08 02:04:23
【问题描述】:
我正在尝试将结构的类型用作我想要得到的函数的通用参数:
type comments []struct {
ID string `json:"id"`
Author string `json:"author"`
Text string `json:"text"`
}
handleReadAll("/getsome")
func handleReadAll(getPath string){
var someVar comments
}
如您所见,我将 someVar 作为类型 cmets,我需要对该类型进行泛型使用,以便可以将 handleReadAll 与泛型类型结构一起使用,这是我迄今为止尝试过的:
handleReadAll("/getsome",comments{})
func handleReadAll(getPath string,structToDecodeArray interface{}){
var object2 reflect.ValueOf(&structToDecodeArray)
var object = reflect.ValueOf(&structToDecodeArray)
fmt.Println("var",object)
fmt.Println("var",reflect.ValueOf(&structToDecodeArray).Interface())
fmt.Println("var",reflect.TypeOf(&structToDecodeArray))
fmt.Println("var",reflect.ValueOf(&structToDecodeArray).Type().Elem)
}
我无法完成这项工作,我正在使用反射来尝试获取参数 structToDecodeArray 的类型,我怎样才能获得相同的 var。
var someVar comments
但有反射。
【问题讨论】:
-
详细解释handleReadAll 的用途。例如,它会从
getPath获取数据并将其解码为 JSON 吗? -
@Cerise Limon 我只想在反映其类型后将其用作常规变量
-
您在寻找类型断言吗?
someVar, ok := structToDecodeArray.(comments). -
好的,我可以这样做,但是有任何这样的投射方式,但需要反射 someVar, ok := structToDecodeArray.(reflectedTypeSomehow)
-
我仍在努力了解您的目标。你将如何处理这个变量?
标签: go reflection types