为什么我不能对空接口进行类型断言?

huangapple go评论125阅读模式
英文:

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)

See https://play.golang.org/p/Xf1TPjSI3_

答案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)

See: https://play.golang.org/p/_BpPqfHYgch

huangapple
  • 本文由 发表于 2017年9月2日 03:21:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/46006748.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定