2017-12-27 08:57
浏览 935


For what I understand type assertion can only be used in interfaces and basically check if a determined type implements the interface.

I am having some weird scenarios:

func binder(value interface{}) {
   // Does not work
   valueInt, ok := value.(int)

   // Works
   valueInt, ok := value.(float64)

   // Does not work 
   coordinates, ok := value.([]int)

   // Does not work 
   coordinates, ok := value.([]float64) 

Basically, my value is an empty interface and I am getting from a json.Unmarshall.

Scenario 1

when I pass a simple integer it does not work but if I check if is a float it works...

Scenario 2

When I pass an array of int or floats does not work! As you can see when I am debugging I am receiving an array but for some reason assertion does not work.

enter image description here

图片转代码服务由CSDN问答提供 功能建议

据我所知,类型断言只能在接口中使用,并且基本上检查确定的类型是否实现了接口。 / p>


  funcinder(value interface {}){
 valueInt  ,ok:= value。(int)
坐标,ok:= value。([[int  )

基本上是我的是一个空接口,我从 json.Unmarshall 获取。




当我传递一个整数数组或浮点数时不起作用! 如您所见,当我调试时,我收到一个数组,但由于某种原因断言不起作用。

”在此处输入图片描述“ \ n

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

  • duan7007 2017-12-27 09:02

    Your question is unclear, but it appears to boil down to the following:

    By default, json.Unmarshal unmarshals all numbers into float64, since all numbers in JSON are floats. If you want some other type, you need to use a specific type in your target type. Examples:

    var x map[string]interface{}
    json.Unmarshal([]byte(`{"foo":123}`), &x) // { "foo": float64(123) }


    var x map[string]int64
    json.Unmarshal([]byte(`{"foo":123}`), &x) // { "foo": int64(123) }

    And by default, all JSON arrays unmarshal to []interface{}, because the members can be of any type, including mixed types. If you want a specific type, again, you have to be specific:

    var x interface{}
    json.Unmarshal([]byte(`[1,2,3]`), &x) // []interface{}{float64(1), float64(2), float64(3)}


    var x []int64
    json.Unmarshal([]byte(`[1,2,3]`), &x) // []int64{1,2,3}
    解决 无用
    打赏 举报

相关推荐 更多相似问题