在GoLang中使用数组符号声明接口

时间:2019-02-23 07:45:50

标签: go interface

我看过的接口定义如下:

type MyInterface interface{
   Method()
}

type MyInterface []interface{
   Method()
}

这两个定义有什么区别?

3 个答案:

答案 0 :(得分:1)

第一个方法是使用interface的方法定义一个Method(),第二个方法是定义slice的一个interface。该语句采用了类型文字的形式,可以被截断为:

type MyInterface [](interface{
   Method()
})

interface{...}此处是类型文字。具有与

相同的效果
type I = interface{
   Method()
}
type MyInterface []I

有关类型文字的更多信息:https://golang.org/ref/spec#Types

注意:MyInterface在第二个名字中会是一个非常糟糕的名字。

答案 1 :(得分:0)

基本上在创建时

type Iface interface {
    Age() uint
    Name() string
}

type SliceIface []interface {
    Age() uint
    Name() string
}

// then SliceIface and []Iface has the same behaviour

所以你可以说

type SliceIface []Iface

看看下面的代码

https://play.golang.org/p/DaujSDZ8p-N

答案 2 :(得分:0)

第一个是接口声明,其中声明了方法method()

type MyInterface interface{
   Method()
}

第二个是类型为[] interface {}的变量不是接口!这是一个切片,其元素类型恰好是interface {}

type MyInterface []interface{
   Method()
}

此外,类型为[] interface {}的变量具有特定的内存布局,在编译时就知道。