面试题答案
一键面试package main
import "fmt"
// Service 服务接口
type Service interface {
Execute()
}
// Worker 结构体
type Worker struct{}
// DoWork Worker的方法,接收Service接口类型参数并调用Execute方法
func (w *Worker) DoWork(s Service) {
s.Execute()
}
// MyService 具体的服务结构体
type MyService struct{}
// Execute MyService实现Service接口的Execute方法
func (m *MyService) Execute() {
fmt.Println("MyService Execute method called")
}
你可以使用以下方式调用:
func main() {
worker := &Worker{}
myService := &MyService{}
worker.DoWork(myService)
}