I am still trying to understand Golang interface. Please correct me and help me understand.
Frances Campoy explains, interface
is a set of contraints.
So in my case, let's say I have one Store
interface that is to be interfaced with contrains, like sort Interface
in Go.
type Store interface {
Earning() int
Expense() int
}
Then what do I have to do if I want to implement this interface constraint to other packages like StoreA
, StoreB
? I want to get a message like when I try:
aa := StoreC{}
aa.Add("AAA")
// error saying `StoreC` does not implement method `Add`, constrained by interface `Store`... something
So what do I do if I want to enforce this contraint in other Store
s? Do I need to do something like inheritance?
type StoreC interface {
Store
}
In other words, I wonder how package sort
's interface of 3 methods can be enforced to every sort
operations in Go. How does it enforce the contraints to any other possible sort
uses in Go?
Thanks!
An interface is mostly useful for a user of the interface. By looking at what methods the interface provides, you know what methods you can safely use.
If you have an interface:
type MyInterface interface {
Frob(int)
Flanged() bool
}
You know that any function func foo(thing MyInterface)
can safely call thing.Frob(..)
and thing.Flanged()
safely.
Any type that implements both a func (r a_type) Frob(int)
and func (r a_type) Flanged() bool
will satisfy the interface. The compiler will do this check at compile-time.
Defining a method looks (roughly) like this:
func (reciever a_type) methodname (possibly more args here) possibly_a_return_type {...}
The receiver's type is the type for which the method is defined. The name of the method comes between and then there's the (possibly empty) argument list.