Golang[]interface{}interface{}
interface{}
Do(ctx, "HKEYS", "KEY")
[]interface{}
func (c *Redis) Do(ctx context.Context, commandName string, args ...interface{}) (interface{}, error) {
	//
    // ...
    //
	reply, err := conn.Do(commandName, args...)
	//
    // ...
    //
	return reply, c.err
}
func (c *conn) Do(cmd string, args ...interface{}) (interface{}, error) {
	return c.DoWithTimeout(c.readTimeout, cmd, args...)
}
func (c *conn) DoWithTimeout(readTimeout time.Duration, cmd string, args ...interface{}) (interface{}, error) {
	//
    // ...
    //
	reply := make([]interface{}, pending)
	//
    // ...
    //
    return reply, err
}
interface{}interface{}implementsinterface{}[]interface{}golanginterface{}
func main() {
	method("string")
	method(123)
	method(make(map[string]int))
	method(make([]interface{}, 0))
	method(true)
}

func method(arg interface{}) {

}
interface{}[]interface{}
[]string[]byte
func main() {
	var a interface{} = method()
	bytes := a.([]byte)
	fmt.Println(bytes)
}

func method() interface{} {
	ans := make([]interface{}, 0)
	return append(ans, []byte{96, 97, 98, 99})
}

然而,编译器狠狠的打了我的脸

interface{}interface{}

了解了相关底层数据存储原理后,这个问题也就迎刃而解了

interface{}
type eface struct {
    _type *_type
    data  unsafe.Pointer
}
interface{}
var (
	a interface{} = 123
	b interface{} = "string"
)
fmt.Println(a == b) // false
[]interface{}
func main() {
	var a = make([]interface{}, 0)
	a = append(a, []int{123, 456})
	a = append(a, []string{"abc", "ijk"})
	fmt.Println(a) // [[123 456] [abc ijk]]
}

但即使切片里存的数据都是某个特定的类型,也不能通过类型断定来强制转换,因为底层的数据存储结构不同

func main() {
	a := method()
	_, ok := a.([]int)
	fmt.Println(ok) // false
}

func method() interface{} {
	var a = make([]interface{}, 0)
	a = append(a, []int{123, 456})
	a = append(a, []int{789, 111})
	return a
}
interface{}[]interface{}[]MyType[]MyType[]interface{}

那么如果我们要把同类型组成的切片转换成的特定类型,可以这样做

func main() {
	a := method()
	ans := make([][]int, 0)
	b, ok := a.([]interface{})
	if ok {
		for _, element := range b {
			ans = append(ans, element.([]int))
		}
	}
	fmt.Println(ans) // [[123 456] [789 111]]
}

func method() interface{} {
	var a = make([]interface{}, 0)
	a = append(a, []int{123, 456})
	a = append(a, []int{789, 111})
	return a
}

参考文章: