代码改变世界

golang常见问题汇总

  youxin  阅读(362)  评论(0编辑  收藏  举报

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

 办法:https://go.dev/tour/methods/15

Type assertions

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

t := i.(T)

This statement asserts that the interface value i holds the concrete type T and assigns the underlying T value to the variable t.

If i does not hold a T, the statement will trigger a panic.

To test whether an interface value holds a specific type, a type assertion can return two values: the underlying value and a boolean value that reports whether the assertion succeeded.

t, ok := i.(T)

If i holds a T, then t will be the underlying value and ok will be true.

If not, ok will be false and t will be the zero value of type T, and no panic occurs.

Note the similarity between this syntax and that of reading from a map.

 

测试一下,将 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 */

 

 

package is folder.

 

package name is folder name.

 

package path is folder path.

 

 

 同一个folder存在不同package, 编译错误:

 

can't load package: package pkg01: found packages pkg01 (pkg01.go) and pkg012 (pkg02.go) in E:\cgss\src\pkg01

 

在同一个folder存在多个package, 则加载失败. 即使是main, 也一样.

 

 

 

 

 

 

如果类型不符呢

测试一下,将 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

相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
历史上的今天:
2014-04-02 yii分页
2014-04-02 MySQL默认INFORMATION_SCHEMA,MySQL,TEST三个数据库用途
2013-04-02 processing ball gravity simulation
2013-04-02 processing bounce ball
2012-04-02 'GetDc' : undeclared identifier
点击右上角即可分享
微信分享提示