DEV Community

Cover image for Most sophisticated embedding pattern in Go: embedded interface within a struct
Lukas Gaucas
Lukas Gaucas

Posted on

Most sophisticated embedding pattern in Go: embedded interface within a struct

From my point of view, this pattern is one of many explanatory examples, but should be learnt by heart until completely comprehended . It's like writing an explicit callback for another callback in JavaScript – takes time to make a final "Gotcha!"

package main

import (
    . "fmt"
)

// 1.3) define interface siganture(s)
type Logic interface {
    Process (data string) string // # signature 1
    /* Argc (data []string) int  */// # signature 2 : keeping 2 as commented out 
}

// 1.1) empty struct is prerequisite to provide a method
type MethodProvider struct {
    isEmpty bool
}

// 1.2) thanks to empty struct above we can define method that will be our implicitly implemented Logic interface field i.e. Process in this case;
// Process method with returning type, in this case, it's a (labeled .......string)
func (methodReceiver MethodProvider) Process(data string) (methodReturnType string) {
    // business logic
    if !methodReceiver.isEmpty {
        Println(data)
    }
    return "methodReceiver that provides implicit Logic.Process signature implementation";
}

// DEV_NOTE: another struct embedding Logic.Process : we say Client "HAS" (i.e. "EMBEDS") Logic.Process not "IS" as embedding vs. inheriting is not the same !
type ClientProvider struct{
    LogicImplementor /* <= is an alias for => */ Logic /* interface */
}

// Program method with returning type, in this case, it's a .....string
func(clientReceiver ClientProvider) Program(pseudo_argv0 string) string {
 // get data from somewhere
    clientReceiver.LogicImplementor.Process("Client Process")
    return "Exit with pseudo code 0";
}

func main() {
    c := ClientProvider{
        LogicImplementor: MethodProvider{},
    }
    Println(c.Program("$PATH_TO_pseudo_argv0.exe"))
}
Enter fullscreen mode Exit fullscreen mode

runnable code example on REPLIT

Open shell instance and type: go run embedded-interf2--advanced.go # <= this might change in the future so don't think hard, think smart !


Related articles :


If you found any typo, or think you can suggest a better solution, please leave a comment below . Stay tuned !

Top comments (0)