DEV Community

Cover image for More explicit interface implementation in Go using simple function signature | 3 ed.
Lukas Gaucas
Lukas Gaucas

Posted on • Updated on

More explicit interface implementation in Go using simple function signature | 3 ed.

NOTE : Go and Golang – are synonyms !

Rather than implicitly stating methodSignature() methodType without any reserved keyword such as implement for method we can write what I call "JavaScript-like callback" i.e. function that wraps interface signature(s) for more explicit interface implementation based upon an arbitrary named convention [2 example]

1 Example – consider initial pseudo_code (Go syntax) :

type someInterface interface {
    methodSignature() methodType
}

// empty struct is still a valid entity to define a method
type yourStruct struct {
  // struct field[s] (if any)
}

func (receiver yourStruct) methodSignature() methodType {
  // method logic
}
Enter fullscreen mode Exit fullscreen mode

2 Example – consider the following optimised pseudo_code (Go syntax) :


package main

import . "fmt"

type someInterface interface {
    methodSignature() methodType
}

// 1/3 empty struct is still a valid entity to define a method
type yourStruct struct {
  // struct field[s] (if any) : empty string would be still valid 
    someType string
}

// 3/3A : wrapper for more explicit interface implementation
func explicitInterface〳implements(interfaceReceiver someInterface){
    interfaceReceiver.methodSignature()
}

// 2/3
func (structAccessor yourStruct) explicitInterface〳implements() /* 3/3B : <= as if written someInterface.methodSignature() but in Golang syntax-enforced fashion  */ {
    Println("Engineering name: " + structAccessor.someType)
}
Enter fullscreen mode Exit fullscreen mode

Practical example (REPL) :

Runnable code example on REPLIT

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


If you found any typo, or think you can suggest a better solution, please leave a comment below . Stay tuned for more coming from Go . Cheers !

Top comments (0)