golang常见问题汇总
2022-04-02 20:40 youxin 阅读(362) 评论(0) 编辑 收藏 举报问题:cannot use variable (type interface {}) as type int in assignment: need type assertion
办法:https://go.dev/tour/methods/15
Type assertions
A 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 typeT
and assigns the underlyingT
value to the variablet
.If
i
does not hold aT
, 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 aT
, thent
will be the underlying value andok
will be true.If not,
ok
will be false andt
will be the zero value of typeT
, 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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需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