Reputation: 19561
After reading the spec, and the "Effective Go" section on them, I still don't quite understand how interfaces work in Go.
Like, where do you define them? How does interface enforcement work? And is there a way to specify somewhere that an object implements an interface, as opposed to simply defining the methods in the interface?
Apologies for the beginner question; but I really am struggling to understand this.
Upvotes: 1
Views: 362
Reputation: 7457
There are some good posts on interfaces over at Russ Cox and Ian Lance Taylor's blog which i recommend checking out. They'll probably cover your questions and more ...
I think a good conceptual example is the net package. There you'll find a connections interface(Conn), which is implemented by the TCPConn, the UnixConn, and the UDPConn. The Go pkg source is probably the best documentation for the Go language.
Upvotes: 3
Reputation: 527378
Basically, you define an interface like this:
type InterfaceNameHere interface {
MethodA(*arg1, *arg2)
MethodB(*arg3)
}
That particular interface definition requires anything which implements the interface to have both a MethodA
method that takes 2 arguments, and a MethodB
method that takes 1 argument.
Once you've defined it, Go will automatically check when you try to use something where a certain interface is required, whether the thing you're using satisfies that interface. You don't have to explicitly state that a given thing satisfies a given interface, it's just automatically checked when you try to utilize something in a scenario where it's expected to satisfy it.
Upvotes: 3