I figured out how to achieve the same thing by myself, even though I enjoyed the “Just learn Go” answers I got.
It’s solved by creating a wrapper function userLoggedInWebEntry
that takes in a WebEntryUserLoggedIn
function signature, but returns a WebEntry
function signature.
It achieves the same thing as the Java inheritance code above, by letting the developer only implement a func( user User ) string
and the logic in userLoggedInWebEntry
is not duplicated
https://play.golang.org/p/adrk46YFIl8
package main
import (
"fmt"
)
type ConnectionData string
type SessionData string
type User string
type WebEntry func(connectionData ConnectionData, sessionData SessionData) string
type WebEntryUserLoggedIn func( user User ) string
func main() {
var webentries []WebEntry
webentries = append( webentries, userLoggedInWebEntry(SavePasswordWebEntry) )
// Test the invocation
fmt.Println( webentries[0]("ConnectionData", "SessionData") )
}
func userLoggedInWebEntry( webEntry WebEntryUserLoggedIn ) WebEntry {
return func(connectionData ConnectionData, sessionData SessionData) string {
// // THIS IS THE LOGIC I DO NOT WANT TO DUPLICATE, HENCE ITS USING CLASS INHERITANCE
var user User = "John"
return webEntry( user )
}
}
func SavePasswordWebEntry( user User ) string {
return fmt.Sprintf("user is %s", user )
}
solved How do I translate this Java interface & inheritence structure to Golang? [closed]