tags:

views:

118

answers:

2

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.

+3  A: 

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.

Amber
Where do you put the type `InterfaceType interface { ... }` though? In your `main` package?
aharon
Wherever you'd plan on using it - the scoping works just like anything else.
Amber
Thanks a lot, Amber. :)
aharon
Go's interfaces let you use duck typing like you would in a purely dynamic language like Python but still have the compiler catch obvious mistakes.
Simon Zimmermann
+2  A: 

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.

Simon Zimmermann
Those posts are excellent. Thanks for the other resources as well.
aharon
Hope you enjoy Go. There are ALOT of QA's in the go-nuts mailing-list as well, which is very active.
Simon Zimmermann