Extending a type

16 views
Skip to first unread message

PeterA

unread,
Oct 18, 2010, 1:34:52 AM10/18/10
to golang-nuts

I'm wondering if anyone knows a good "pattern" for enhancing an
existing type.

Lets assume there exists

type Point struct { x, y int }

func (p Point) Translate(dx, dy int) Point {

}

fango

unread,
Oct 18, 2010, 1:43:23 AM10/18/10
to golang-nuts
You mean

type ColorPoint struct { color int; Point };
var p ColorPoint;
p.Translate(-1, -1)

Cheers,
Fango

PeterA

unread,
Oct 18, 2010, 2:04:56 AM10/18/10
to golang-nuts

I'm wondering if anyone knows a good "pattern" for enhancing an
existing type...

Lets assume there exists:

type Point struct { X, Y int }

func (p *Point) Translate(dx, dy int) {
p.X += dx
p.Y += dy
}

and I want to create a new type with an additional method. If I just
create a new type with a different name, the new type doesn't
implement Translate:

type MyPoint Point

which is fair enough, I guess, since *MyPoint isn't the same thing as
*Point.
But if I embed Point in MyPoint, all is well:

type MyPoint struct { Point }

var p MyPoint

p.X, p.Y = 1, 1 // I can get to the fields of Point because of the
rules of embedding

However, if I want to initialise MyPoint with a composite literal, I
have to expose the fact that MyPoint contains a Point:

var p = MyPoint{Point{1, 2}} // now I've lost the abstraction
of my implementation

Further, the rules that let me access p.X, p.Y don't seem to extend to
composite literals, ie. I can't go:

var p = MyPoint{X: 1, Y: 1}

I suppose this could all be solved by having an "Init" method. If so,
what's the preferred way of doing this?

Thanks in advance,

PeterA




yy

unread,
Oct 18, 2010, 4:02:25 AM10/18/10
to PeterA, golang-nuts
2010/10/18 PeterA <peter.a...@gmail.com>:

> I suppose this could all be solved by having an "Init" method. If so,
> what's the preferred way of doing this?

I'd say the most idiomatic way would be with a New function:

type Point struct { otherpkg.Point }

func NewPoint(x, y int) Point {
return Point{otherpkg.Point{1, 2}}
}

A New function will be needed anyway if you have private fields. In my
opinion Init is a better name if you really have to do some
initialization, like for example making channels and launching
goroutines, while New is better for an example like yours.

--
- yiyus || JGL . 4l77.com

Peter Allworth

unread,
Oct 18, 2010, 6:42:01 AM10/18/10
to yy, golang-nuts
Thanks! That makes a lot of sense. I like NewPoint (or NewMyPoint), it looks very clean.

Apologies, BTW, for the partial post at the start of this thread.
I clicked a button I shouldn't have halfway through writing my question. :-(

Cheers,
PeterA
Reply all
Reply to author
Forward
0 new messages