tags:

views:

235

answers:

2

I found an interesting blog post about Go. I am trying to understand the concept of interfaces, but I find it very hard to do so from the code fragment in the blog post, and nearly impossible from the language specification. Can anyone point out a simple example of Go's interfaces in a working program?

+1  A: 

The base concept of interfaces in Go, is that any object implementing a method defined an interface, can be a part of that interface.

The best example is the Writer interface. Rob Pike has an example of this in his intro speech at Google Tech Talk ( http://www.youtube.com/watch?v=rKnDgT73v8s ) - scroll to 33:25 into the speech for his explanation.

Björn
Thanks, but I really would like a complete piece of code.
Kinopiko
+2  A: 

It's a work-in-progress learning exercise, and certainly a poor example of good style, but here you go (spec).

Additionally, as a more exotic example, I made a post on the go-nuts mailing list regarding using interface{} for building functions that work with anonymous data (in this case, a "ternary operation" function):

package main
import "fmt";
func Tern(exp bool, a interface{}, b interface{}) (interface{}) {
    if exp { return a }
    return b
}
func main() {
    a := 7; b := 1;
    result := Tern(a > b, a, b);
    fmt.Printf("%d\n", result);
}
esm
Thanks, I'll have a look at your example. I want a piece of compiling code to work with so this looks good.
Kinopiko
What does `interface{}` mean here?
Kinopiko
"interface{}" is an empty interface; in other words, it matches all types. Think of it as an "any" value: a means of writing generic functions that can operate on any value. Sadly, the documentation sorely lacks here; this, along with the "reflection" package, give you some really interesting options for type manipulation.
esm
I was looking at some of the library code about `reflect` but ended up a bit confused. It's used a lot in the `Printf` routines where the type of the variables is got from the variables themselves. But I got lost in a twisty maze of dependencies, all alike.
Kinopiko