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