gpt4 book ai didi

go - 接口(interface)实现数组和调用额外函数

转载 作者:行者123 更新时间:2023-12-01 22:43:47 25 4
gpt4 key购买 nike

我的应用程序中有一些服务概念
服务接口(interface)定义如下

type Service interface {
// Init and Start the Service
Start() error
// Start the Service
// Stops the Service
Stop() error
}

使用此接口(interface)实现了几种类型
type Service1 struct {  
}
func NewService1() *Service1 {
return &MediaService{}
}
func (m *Service1) Start() error {
}
func (m *Service1) Stop() error {
}
func (m *Service1) Fn1() error {
}


type Service2 struct {  
}
func NewService2() *Service2 {
return &MediaService{}
}
func (m *Service2) Start() error {
}
func (m *Service2) Stop() error {
}
func (m *Service2) Fn2() error {
}

将所有实例存储在数组中
Services = make([]Service, 2)

Services[0] = NewService1()
Services[1] = NewService2()

但我不能调用服务中定义的额外函数。
Services[0].Fn1Services[1].Fn2

最佳答案

Services = make([]Service, 2)表示你有一个接口(interface)数组Service
哪个 Service 并不重要只要实现满足 Service契约(Contract),命名为 Start() errorStop() error
当您从该阵列获得服务时:
Services[0]
在编译时 this if 的类型为 Service因此您只能访问 Service 的所有功能.

在运行时,Services[0] 后面的实际类型是 NewService1或者可能是另一个,但这并不重要,因为您指定了 Services数组类型为 Service因此只能访问这些功能。

如果你真的想调用Fn1 ,您必须假设哪个实际类型位于单个数组字段的后面并强制转换它们:
Services[0].(*Service1).Fn1()
如果你想避免在运行时因为无效的强制转换而出现 panic (当不同的类型如果你期望的那样实际可用时),请在这里查看你如何进行类型断言 https://golang.org/ref/spec#Type_assertions

关于go - 接口(interface)实现数组和调用额外函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60297003/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com