Reputation: 5389
I have seen interfaces defined like:
type MyInterface interface{
Method()
}
and
type MyInterface []interface{
Method()
}
What is the difference in these two definitions?
Upvotes: 2
Views: 252
Reputation: 587
The first one is an interface declaration with a method method()
declared in it.
type MyInterface interface{
Method()
}
The second is that a variable with type []interface{} is not an interface! It is a slice whose element type happens to be interface{}
type MyInterface []interface{
Method()
}
Plus, a variable with type []interface{} has a specific memory layout, known at compile time.
Upvotes: 0
Reputation: 444
Basically when you create
type Iface interface {
Age() uint
Name() string
}
type SliceIface []interface {
Age() uint
Name() string
}
// then SliceIface and []Iface has the same behaviour
so you could say
type SliceIface []Iface
Have a look at following code
https://play.golang.org/p/DaujSDZ8p-N
Upvotes: 0
Reputation: 8232
The first is defining an interface
with a method of Method()
, while the second is defining the a slice
of interface
. The statement utilizes the form of type literal and can be interepted as:
type MyInterface [](interface{
Method()
})
Where interface{...}
here is a type literal. Which has the same effect of
type I = interface{
Method()
}
type MyInterface []I
See more on type literal: https://golang.org/ref/spec#Types
Note: MyInterface
would be a very bad name in the second one.
Upvotes: 1