Skip to content

Instantly share code, notes, and snippets.

@termie
Last active January 20, 2016 19:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save termie/8b66a2b4206e8e042766 to your computer and use it in GitHub Desktop.
Save termie/8b66a2b4206e8e042766 to your computer and use it in GitHub Desktop.
partial implementation mixin class from another package?
package basepackage
type Box interface {
Width() int
Height() int
Color() string
}
type BaseBox struct {
width int
height int
// and a bunch more properties
// ...
}
func (b *BaseBox) Width() int {
return b.width
}
func (b *BaseBox) Height() int {
retrn b.height
}
package otherpackage
type RGBBox struct {
*basepackage.BaseBox
r, g, b int
}
func (b *RGBBox) Color() string {
return fmt.Sprintf("%s%s%s", hex(b.r), hex(b.g), hex(b.b))
}
func NewRGBBoxFromConfig(config *RGBBoxConfig) *RGBBox {
// this is what I conceptually want to do, but it will fail
// because BaseBox does not export these fields, possible solutions
// below
base := basepackage.BaseBox{
width: config.Width,
height: config.Height,
// ...
}
return &RGBBox{
BaseBox: &base,
r: config.Red,
g: config.Green,
b: config.Blue,
}
}
// Option 1:
// copy the BaseBox implementation to otherpackge
// - somewhat negates the point of having a partial impl, two places to make updates
// Option 2:
// expose all the fields and give them different names to not interfere with the exposed methods
// - the internal field names start looking silly
// Option 3:
// create a NewBaseBox that takes as arguments a big list of fields
// - the example above only has two, but the real code has about 8
// Option 4:
// option 3 but using an "Options" struct with exposed fields as the argument to NewBaseBox
// - is effectively option 2 without the weird names but with an intermediate struct duplicating
// the internal structure
// Of these option 4 requires the smallest code change, but perhaps there is an option 5 that is more go-y?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment