提问人:Ndifreke 提问时间:6/4/2023 更新时间:6/4/2023 访问量:40
如何将复合接口类型强制转换为其实现类型
How to cast a composite interface type to it implementation type
问:
我有一个简单的函数,它返回一个由结构体完全实现的接口映射。有没有办法将复合地图投射到?LockInterface
InterfaceImpl
LockInterface
InterfaceImpl
当我写这个问题时,我想到了一个解决方案,那就是将个人价值投射到新地图上,但我仍然很好奇是否有更简单的方法可以做到这一点。map[string]LockInterface
map[string]LockImpl
我的目标是能够.请注意 B() 不在接口签名中LockList()["foo"].B()
type LockInterface interface {
A()
}
//fully implements lockInterface
type LockImp struct {
x string
}
func (a LockImp) A() {}
func (l Lock) B() {
}
//factory
func NewLock() LockInterface {
return &LockImp{}
}
func LockList()map[string]LockInterface{
return make(map[string]LockInterface)
}
func main() {
//Not okay
// invalid operation: list (variable of type map[string]LockInterface) is not an interface
list := LockList()
a, b := list.(map[string]LockImp)
//Okay
// list := LockList()[""]
// a, b := list.(LockImp)
}
答: 暂无答案
评论
LockImp
B
LockImp
Lock