cannot use variable (type interface {}) as type int in assignment: need type assertion

更新日期: 2020-07-08 阅读次数: 9023 字数: 290 分类: golang

在使用 golang gin 时,通过 context get 获取的值在赋值给一个整型变量时,报错

cannot use variable (type interface {}) as type int in assignment: need type assertion

代码模拟如下:

package main

import "fmt"

func main() {
	var tmp interface{}
	var i int
	tmp = 1
	i = tmp
	fmt.Println(i)
}

报错的代码行是 i = tmp 那行。

可见,interface{} 类型可以被任何类型赋值,但是 interface{} 不可以直接给其他类型赋值。

解决方法

//i = tmp
i = tmp.(int)

什么是 type assertion

https://tour.golang.org/methods/15

A type assertion provides access to an interface value's underlying concrete value.

概况来说,type assertion 就是提供了 interface{} 类型转换的方法。

如果类型不符呢

测试一下,将 interface{} 的值换成字符串类型。

func main() {
	var tmp interface{}
	var i int
	tmp = "golang 性能不错"
	i = tmp.(int)
	fmt.Println(i)
}

程序直接 panic ...

panic: interface conversion: interface {} is string, not int

更严谨的处理方法

i, ok = tmp.(int)

// or
if i, ok := tmp.(int); ok {
    /* act on int */
} else {
    /* not int */
}

在 ok 为 true 时,说明类型转换成功。

tags: type assertion

关于作者 🌱

我是来自山东烟台的一名开发者,有敢兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊, 查看更多联系方式