convert interface{} to int in Golang

匿名 (未验证) 提交于 2019-12-03 01:58:03

问题:

I'm new to Golang and I'm trying to get a value from a JSON and cast it to int but it doesn't work. Don't know how to do it properly.

Here is the error message:

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

And the Code:

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

any help would be appreciated.

回答1:

Instead of

iAreaId := int(val) 

you want a type assertion:

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

The reason why you cannot convert an interface typed value are these rules in the referenced specs parts:

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.

But

iAreaId := int(val) 

is not any of the cases 1.-7.



回答2:

I am assuming: If you sent the JSON value through browser then any number you sent that will be the type float64 so you cant get the value directly int in golang.

So do the conversion like:

//As that says: fmt.Fprintf(w, "Type = %v", val) //

var iAreaId int = int(val.(float64))

This way you can get exact value what you wanted.



回答3:

I whole-heartedly agree with zzzz's type assertion answer and I strongly prefer that way over others. That said, here's what I've had to do when the preferred method has not worked... (long story related to cross-serialization of data). You can even chain this into a switch statement with case errInt == nil and similar expressions.

package main  import "fmt" import "strconv"  func main() {     var v interface{}     v = "4"      i, errInt := strconv.ParseInt(v.(string), 10, 64)      if errInt == nil {         fmt.Printf("%d is a int", i)         /* do what you wish with "i" here */     } } 

Like I said above, try type assertion first before trying this way.



回答4:

To better understand the type conversion, look at the code below:

package main import "fmt" func foo(a interface{}) {     fmt.Println(a.(int))  // conversion of interface into int } func main() {     var a int = 10     foo(a) } 

This code executes perfectly and converts interface type to int type

For an expression x of interface type and a type T, the primary expression x.(T) asserts that x is not nil and that the value stored in x is of type T. The notation x.(T) is called a type assertion. More precisely, if T is not an interface type, x.(T) asserts that the dynamic type of x is identical to the type T. In this case, T must implement the (interface) type of x; otherwise the type assertion is invalid since it is not possible for x to store a value of type T. If T is an interface type, x.(T) asserts that the dynamic type of x implements the interface T.

Going back to your code, this

iAreaId := val.(int)

should work good. If you want to check error occured while conversion, you can also re-write above line as

iAreaId, ok := val.(int)



回答5:

You need to do type assertion for converting your interface{} to int value.

iAreaId := val.(int) iAreaId, ok := val.(int)`\ 

More information is available.



回答6:

Best avoid casting by declaring f to be f the correct type to correspond to the JSON.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!