MST

星途 面试题库

面试题:Go中如何实现简单的接口回调机制示例

请编写一个Go程序,展示如何利用接口回调机制,假设有一个服务接口 `Service` ,包含一个 `Execute` 方法,有一个 `Worker` 结构体,它的某个方法接收 `Service` 接口类型参数,并在内部调用 `Execute` 方法,然后实现具体的服务结构体并传递给 `Worker` 方法进行回调。
32.4万 热度难度
编程语言Go

知识考点

AI 面试

面试题答案

一键面试
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)
}