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

报告相同问题?

悬赏问题

  • ¥15 关于#python#的问题:求帮写python代码
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?