Interfaces in Go are very different from interfaces in Java.
In Java a class has to formally agree to implement an interface:
public class Foo implements iFoo
In Go a user type implements an interface by simply doing so.
A function or property can then define what is expected:
func DoSomething(r io.Reader) {
buf := make([]byte, 128)
n, err := r.Read(buf)
...
}
The DoSomething
function can be passed anything that implements the Read
function found in the io.Reader
interface, without the thing knowing or caring about the interface. It is the responsibility of the caller to make sure it is passing in something that implements the interface. This is checked at compile time.
We can take this a step further. We can define our own interface:
type MyInterface interface {
io.Reader // Include Reader interface
Seek(int) error // Include my own function
}
func DoSomething(r MyInterface) {
buf := make([]byte, 128)
n, err := r.Read(buf)
...
}
Go is also different in that it doesn't have a class or object type. Any user declared type, whether it be based on an integer, string, struct, array, slice, channel, etc. can have methods attached to it.
Go also doesn't have typical class-like inheritance you're normally used to, but it does have a couple of things that are pretty close.
Redeclared type:
type Num int
func (n Num) Print() {
print(n)
}
type Number Num
func (n Number) Print() {
Num(n).Print()
}
Anonymous fields:
type Foo struct {
sync.Mutex
}
func main() {
f := Foo{}
f.Lock()
// ...
f.Unlock()
}