英文:
Why I cannot type assert empty interface?
问题
我想将空接口转换为映射。为什么这样不行?
// q tarantool.Queue (https://github.com/tarantool/go-tarantool)
statRaw, _ := q.Statistic() // interface{}; map[tasks:map[taken:0 buried:0 ...] calls:map[put:1 delay:0 ...]]
type stat map[string]map[string]uint
_, ok := statRaw.(stat)
英文:
I would like to cast empty interface to map. Why is this not ok?
// q tarantool.Queue (https://github.com/tarantool/go-tarantool)
statRaw, _ := q.Statistic() // interface{}; map[tasks:map[taken:0 buried:0 ...] calls:map[put:1 delay:0 ...]]
type stat map[string]map[string]uint
_, ok := statRaw.(stat)
答案1
得分: 3
你的函数返回的是map[string]map[string]uint
,而不是stat
。它们在Go的类型系统中是不同的类型。你可以使用类型断言来将其转换为map[string]map[string]uint
,或者在Go 1.9中,你可以创建一个别名:
statRaw, _ := q.Statistic()
type stat = map[string]map[string]uint
_, ok := statRaw.(stat)
参考链接:https://play.golang.org/p/Xf1TPjSI3_
英文:
Your function returns a map[string]map[string]uint
, not a stat
. They are distinct types in go's type-system. Either type-assert to map[string]map[string]uint
or, in Go 1.9, you can create an alias instead:
statRaw, _ := q.Statistic()
type stat = map[string]map[string]uint
_, ok := statRaw.(stat)
答案2
得分: 0
不要为这种情况使用类型别名。
首先进行类型检查,然后进行转换:
statRaw, _ := q.Statistic()
raw, ok := statRaw.(map[string]map[string]uint)
if !ok {
return
}
type stat map[string]map[string]uint
my := stat(raw)
参考链接:https://play.golang.org/p/_BpPqfHYgch
英文:
Don't use a type alias for this kind of thing.
First type check, then convert:
statRaw, _ := q.Statistic()
raw, ok := statRaw.(map[string]map[string]uint)
if !ok {
return
}
type stat map[string]map[string]uint
my := stat(raw)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论