Use the same methods for different structs

I have two structs which they both have the same methods:

func (r *myStruct1) DoThis() error {}
func (r *myStruct1) DoThat() error {}

func (r *myStruct2) DoThis() error {}
func (r *myStruct2) DoThat() error {}

I don’t like the duplication here, since they are actually both doing the same thing, just for different structs. Is there any way to generalise them? If so, could you perhaps come up with a code example?

This is called composite design pattern.

package main

import "fmt"

type myStruct1 struct {
	method func()
}

type myStruct2 struct {
	method func()
}

func doThis() {
	fmt.Println("test")
}

func main() {

	struct1 := myStruct1{
		method: doThis,
	}

	struct2 := myStruct1{
		method: doThis,
	}

	struct1.method()
	struct2.method()
}
1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.