Why I cannot type assert empty interface?

150 Views Asked by At

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)
2

There are 2 best solutions below

0
On

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_

0
On

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