## Playing with Go's Interfaces (images)

From: andrew cooke <andrew@...>

Date: Mon, 11 Jul 2011 21:12:54 -0400

Look what I've just done :o)

func TestImage (t *testing.T) {
var b1, b2 bytes.Buffer

r := image.NewRGBA64(10,20)
r.Set(2, 3, image.RGBA64Color{0xffff, 0, 0, 0xffff})
r.Set(3, 2, HSVAColor{120, 1, 1, 1})
err := png.Encode(&b1, r)
fmt.Println(err)
fmt.Println(&b1)

h := NewHSVA(10,20)
h.Set(2, 3, HSVAColor{0, 1, 1, 1})
h.Set(3, 2, image.RGBA64Color{0, 0xffff, 0, 0xffff})
err = png.Encode(&b2, h)
fmt.Println(err)
fmt.Println(&b2)

fmt.Println(string(b1.Bytes()) == string(b2.Bytes()))
}

In case that's not totally obvious (what, you have a life?), it's a test that
shows I've successfully added a new colour type (HSVA) to Go's image library.
That means that I can use HSV values, as well as the standard RGB, to
construct images and then write them out to PNG files, etc.

There's nothing here that you couldn't have done with Java's interfaces - that
it's possible to extend the system is mainly down to whoever wrote the library
doing so around interfaces that anyone can implement - but it's way better
(safer) than anything you might have attempted in C.

The code also demonstrates an interesting aspect of Go that took me some time
to understand.  If you look at the documentation for buffers -
http://golang.org/pkg/bytes/#Buffer - it's not obvious how you make a new one.
There's a constructor for wrapping a string or byte array, but those are for
when you want the buffer to contain something initially (it's not backing
storage either - these things grow as necessary).

What's important is the phrase "The zero value for Buffer is an empty buffer
ready to use".  What that means is that to get a new, empty buffer, you just
declare it.  Which is what I do (twice) on the first line of the test.

(And yes, that's not really a very good test as it doesn't assert anything -
I'm going to fix that now).

Andrew