代码改变世界

golang常见问题汇总

2022-04-02 20:40  youxin  阅读(337)  评论(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