dor65412
2017-12-27 08:57
浏览 935
已采纳

Golang类型断言数组

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)
 
 //有效
 valueInt,ok:=值。(float64)
 
 //不起作用
坐标,ok:= value。([[int  )
 
 //无法使用
坐标,好的:=值。([[float64)
} 
   
 
 

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

场景1

当我传递一个简单的整数时,它不起作用,但是如果我检查它是否是浮点数,则可以......

方案2

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

”在此处输入图片描述“ \ 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) }
    

    vs:

    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)}
    

    vs:

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

相关推荐 更多相似问题