Dev Notes

Software Development Resources by David Egan.

Add Methods To An Existing Type in Go

David Egan

Code re-use in object-oriented Go is achieved by means of composition rather than inheritance.

Composition means that an object contains another object (“has a …”) rather than extending another object(“is a …”).

Instead of overriding functions, function calls are delegated to the internal object.

Add Method to An Existing Type

You can modify a type locally by type definition or embedding.

Type Definition

Create an alias to the external type.

  • Provides direct access to fields of the external type
  • DOES NOT provide access to methods of the external type

// Parent is a type defined in package-name with a field FamilyName and a method GetFamilyName
type child package-name.Parent

name := child.FamilyName // OK

name := child.GetFamilyName() // Won't work unless the method is defined specifically on child


Embedding is a Go feature that eases type composition.

If a type A is included as a nameless parameter in type B, then the methods defined on type A are accessible through type B.

The compiler uses the concept of promotion to export properties & methods of the embedded type to the embedding type.

If a type contains a field of another type, but no name is assigned to that field, it is an embedded field.

Fields or methods on the embedded field are promoted to the containing struct.

If types are listed within a struct without giving them field names, they are embedded. This promotes the methods of the embedded types - they are available to the containing type. The local type then:

  • Has access to all fields of the parent
  • Has access to methods of the parent - they are promoted to the local type
  • If the embedded type is a pointer, it must be initialised separately
  • You can’t embed a non-struct type within a struct and get access to the parent methods


comments powered by Disqus