从我的角度来看,这种模式是众多解释性示例之一,但应该在心中学到直到完全理解。这就像在JavaScript中为另一个回调编写一个明确的回调 - 需要时间才能制作最终的“ 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"))
}
runnable code example on REPLIT
open shell实例和类型:
go run embedded-interf2--advanced.go
#<=这可能会在将来发生变化,所以不要想,请思考智能!
相关文章:
如果您发现任何错别字,或者认为您可以提出更好的解决方案,请在下面发表评论。敬请期待!