Libove Blog

Personal Blog about anything - mostly programming, cooking and random thoughts

Inheritance Pattern in Go

Go isn't an object oriented language and doesn't have inheritance. Sometimes I still want to model something in a similar way as I would in an object oriented languages. My blog software has different types of "entries", e.g. articles, images, recipes ... This is modeled by an interface Entry which has to be implemented by each type of post.

// truncated for simplicity
type Entry interface {
	ID() string
	Content() EntryContent
	PublishedAt() *time.Time
	Title() string
	SetID(id string)
	SetPublishedAt(publishedAt *time.Time)
}

One problem with this is, that I have to implement these functions for each type of entry. Many of these implementation will be identical leading to a high degree of code duplication. To avoid this I've created an EntryBase, which implements sensible defaults.

type EntryBase struct {
	id          string
	publishedAt *time.Time
}

func (e *EntryBase) ID() string {
	return e.id
}

func (e *EntryBase) PublishedAt() *time.Time {
	return e.publishedAt
}

func (e *EntryBase) SetID(id string) {
	e.id = id
}

func (e *EntryBase) SetPublishedAt(publishedAt *time.Time) {
	e.publishedAt = publishedAt
}

With this "base class" the specific implementations only have to implement functions which differ between entry types.

type Article struct {
	EntryBase
	meta ArticleMetaData
}

type ArticleMetaData struct {
	Title   string
	Content string
}


func (e *Article) Title() string {
	return e.meta.Title
}

func (e *Article) Content() model.EntryContent {
    // render content from markdown	
}