我看过的接口定义如下:
type MyInterface interface{
Method()
}
和
type MyInterface []interface{
Method()
}
这两个定义有什么区别?
答案 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
看看下面的代码
答案 2 :(得分:0)
第一个是接口声明,其中声明了方法method()
。
type MyInterface interface{
Method()
}
第二个是类型为[] interface {}的变量不是接口!这是一个切片,其元素类型恰好是interface {}
type MyInterface []interface{
Method()
}
此外,类型为[] interface {}的变量具有特定的内存布局,在编译时就知道。