C# has Extension Methods, which allow you to add methods to existing types, regardless of where they are defined by you or in a third-party assembly.

Go has receiver methods, which are functions that are called on a value of a specific type. The type has to be defined within your package, and the receiver is the value that is being passed to the method.

I wanted to accomplish a similar behavior in Go.

Check out the repo here: https://github.com/ElanHasson/go-experiments-kinda-extension-methods.

I figured out how to creating a struct of the struct I wanted to extend.

There is one caveat here: You must implement all methods the base struct has, even if they are empty, otherwise if you call it, you’ll get a runtime panic.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package main

import (
	"fmt"

	"github.com/ElanHasson/go-experiments/common"
)

type SomethingElse common.Something

func (m *SomethingElse) DoSomething() {
	fmt.Println("somethingElse.DoSomething()")
}

func (m *SomethingElse) DoNothing() {
	fmt.Println("somethingElse.DoNothing()")
}

func main() {
	something := common.Something{Name: "Hello"}

	somethingElse := SomethingElse(something)

	somethingElse.DoSomething()
	somethingElse.DoNothing()

	fmt.Printf("something: %v\n", something)
	fmt.Printf("somethingElse: %v\n", somethingElse)
}