[英]In Go, Given an interface{} in which I know what interface it implements, how can I convert to it
[英]How to convert interface to another interface which it implements?
簡而言之- 我希望能夠將其基礎類型實現特定接口的接口類型轉換為該特定接口。
我正在使用插件 package 查找新的 function,它看起來像這樣(我有很多其他的相同):
func NewDomainPrimaryKey() any { return DomainPrimaryKey{} }
(這是在運行時生成的,所以我不能將它作為 DomainPrimaryKey 引用)
我的查找和調用是這樣的:
plugin, err := plugin.Open("my-plugin")
if err != nil {
return err
}
symGet, err := plugin.Lookup("New" + pluginName)
if err != nil {
return err
}
newGenModel, ok := symGet.(func() any)
if !ok {
return errors.New("unexpected type from module symbol")
}
anyGenModel := newGenModel()
genModel, ok := anyGenModel.(GenModel) // **this is where the problem is
if !ok {
return errors.New("unexpected type from module symbol")
}
genModelInstance := genModel.Get()
在上面,我試圖將“anyGenModel”(一個接口)轉換為它實現的“GenModel”接口,但是,這不起作用。
我確定它實現了這個接口,因為當我執行以下操作時,我沒有收到任何錯誤。
type GenModel interface {
Get() any
TableName() string
}
var _ GenModel = (*DomainPrimaryKey)(nil) // this doesn't complain
我怎樣才能做到這一點? 我發現這篇文章我認為不是我要找的,但看起來很相似。
預先感謝您對此提供的任何幫助 - 這對我來說已經成為一個真正的障礙。
如果底層類型實現了這兩個接口,這就非常簡單了:
package main
import "fmt"
type IFace1 interface {
DoThis()
}
type IFace2 interface {
DoThat()
}
type impl struct{}
func (i *impl) DoThis() {
fmt.Println("I implement IFace1")
}
func (i *impl) DoThat() {
fmt.Println("I implement IFace2")
}
func GetIFace1() IFace1 {
return &impl{}
}
func main() {
i1 := GetIFace1()
i1.DoThis()
i2 := i1.(IFace2)
i2.DoThat()
}
如果您的代碼無法正常工作,那么我會首先質疑您關於anyGenModel
的基礎類型實際上實現GenModel
並從那里開始工作的斷言。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.