gpt4 book ai didi

go - 将 interface{} 转换为 int

转载 作者:IT老高 更新时间:2023-10-28 12:57:33 25 4
gpt4 key购买 nike

我正在尝试从 JSON 中获取一个值并将其转换为 int,但它不起作用,我不知道如何正确执行。

这是错误信息:

...cannot convert val (type interface {}) to type int: need type assertion

还有代码:

    var f interface{}
err = json.Unmarshal([]byte(jsonStr), &f)
if err != nil {
utility.CreateErrorResponse(w, "Error: failed to parse JSON data.")
return
}

m := f.(map[string]interface{})

val, ok := m["area_id"]
if !ok {
utility.CreateErrorResponse(w, "Error: Area ID is missing from submitted data.")
return
}

fmt.Fprintf(w, "Type = %v", val) // <--- Type = float64
iAreaId := int(val) // <--- Error on this line.
testName := "Area_" + iAreaId // not reaching here

最佳答案

代替

iAreaId := int(val)

你想要一个 type assertion :

iAreaId := val.(int)
iAreaId, ok := val.(int) // Alt. non panicking version

你不能convert的原因接口(interface)类型值是引用规范部分中的这些规则:

Conversions are expressions of the form T(x) where T is a type and x is an expression that can be converted to type T.

...

A non-constant value x can be converted to type T in any of these cases:

  1. x is assignable to T.
  2. x's type and T have identical underlying types.
  3. x's type and T are unnamed pointer types and their pointer base types have identical underlying types.
  4. x's type and T are both integer or floating point types.
  5. x's type and T are both complex types.
  6. x is an integer or a slice of bytes or runes and T is a string type.
  7. x is a string and T is a slice of bytes or runes.

但是

iAreaId := int(val)

不是任何一种情况 1.-7.

关于go - 将 interface{} 转换为 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18041334/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com