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

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

  • 写回答

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}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 adb连接不到手机是怎么回事?
  • ¥15 vs2022无法联网
  • ¥15 TCP的客户端和服务器的互联
  • ¥15 VB.NET操作免驱摄像头
  • ¥15 笔记本上移动热点开关状态查询
  • ¥85 类鸟群Boids——仿真鸟群避障的相关问题
  • ¥15 CFEDEM自带算例错误,如何解决?
  • ¥15 有没有会使用flac3d软件的家人
  • ¥20 360摄像头无法解绑使用,请教解绑当前账号绑定问题,
  • ¥15 docker实践项目