而不是明确说明methodSignature() methodType
的方法,我们可以编写我所谓的“ JavaScript类似回调”的内容,即包装接口签名的功能,以获取更多隐式[2示例]
1示例:初始考虑
type someInterface interface {
methodSignature() methodType
}
// empty struct is still a valid entity to define a method
type yourStruct struct {
// struct fields (if any)
}
func (receiver yourStruct) methodSignature() methodType {
// method logic
}
2示例
type someInterface interface {
methodSignature() methodType
}
// empty struct is still a valid entity to define a method
type yourStruct struct {
// struct fields (if any)
}
func implement_someInterface(receiver yourStruct){
receiver.methodSignature()
}
// convetion how to prefix e.g. implement_ or using camelcase is a matter of convetion
func (receiver yourStruct) implement_someInterface() {
// method logic
}
实践示例:
package main
import . "fmt"
// It is modified version for ALTERNATIVE B, but mainly based on this tutorial TutorialEdge@https://www.youtube.com/watch?v=PCW7fDta-BE&t
type Employee interface {
GetName() string
}
// ALTERNATIVE B 1/2
func implementEmployee(r Employee){
r.GetName()
}
type Engineer struct{
Name string
}
// ALTERNATIVE A 1/1
// func (e Engineer) GetName() string /* implements Employee */ {
// Println("Engineering name: " + e.Name)
// return ""
// }
// ALTERNATIVE B 2/2
func (e Engineer) implementEmployee() {
Println("Engineering name: " + e.Name)
/* return; */
}
func main(){
eg1 := Engineer{Name: "John"}
/* eg1.GetName() */// PART OF ALTERNATIVE A
eg1.implementEmployee()
}
Runnable code example on REPLIT
open shell实例和类型:
go run implementInterfaceWrapper.go
#<=这可能会在将来发生变化,所以不要想,请思考智能!
如果您发现任何错别字,或者认为您可以提出更好的解决方案,请在下面发表评论。敬请期待!