面试题答案
一键面试- 安装Go inject库:
go get github.com/gojuno/minimock/v3/gomock go get github.com/gojuno/minimock/v3
- 定义服务接口和实现:
// 定义服务接口 type Service interface { DoSomething() string } // 服务接口的实现 type ServiceImpl struct{} func (s *ServiceImpl) DoSomething() string { return "Service is doing something" }
- 使用Go inject库进行依赖注入:
package main import ( "fmt" "github.com/gojuno/minimock/v3" ) func main() { ctrl := minimock.NewController() defer ctrl.Finish() // 创建ServiceImpl实例 service := &ServiceImpl{} // 模拟注入,这里简单的将service传递给需要的组件 component := NewComponent(service) result := component.UseService() fmt.Println(result) } // 定义需要Service的组件 type Component struct { service Service } // 创建组件并注入Service func NewComponent(service Service) *Component { return &Component{service: service} } // 组件使用Service的方法 func (c *Component) UseService() string { return c.service.DoSomething() }
上述代码首先定义了服务接口Service
及其实现ServiceImpl
,然后在main
函数中创建ServiceImpl
实例,并将其注入到Component
组件中,Component
通过调用注入的Service
来执行相关操作。需要注意,这里简单模拟了依赖注入的过程,实际的go inject
库可能有更复杂的功能和使用方式。