【问题标题】:How to get the type of a parameter on a function如何获取函数的参数类型
【发布时间】: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


【解决方案1】:

经过一些测试,我设法得到它,我向函数发送了错误的参数,我将它更改为这个

var paramVar comments
handleReadAll("/getsome",paramVar)

func handleReadAll(getPath string,structToDecodeArray interface{}){
      var someVar = reflect.ValueOf(structToDecodeArray).Interface()
}

这将是与传递给函数的参数的类型接口等效的变量,就像拥有

var someVar comments 

【讨论】:

  • var someVar = reflect.ValueOf(structToDecodeArray).Interface() 可以更直接地写成var someVar = structToDecodeArray
  • 天哪,在我猜我只需要更改参数之前,我得到了一个接口类型,非常感谢老兄!
  • @CeriseLimón cast vs type.Assertion?,我是新人。
猜你喜欢
  • 2020-08-22
  • 1970-01-01
  • 2017-09-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多