Símbolo de plug-in como retorno de função
Estou tendo um comportamento Go que não entendo. Minha idéia é importar um plug-in que implementa uma interface que está fora dos dois pacotes. Se uma estrutura é retornada, ela funciona bem, mas para ter certeza de que implementa a interface, desejo retornar uma interface que falhe.
Definição da interface:
package iface
type IPlugin interface{
SayHello(string)
SayGoodby(string)
WhatsYourName() string
}
O programa principal fica assim:
package main
import (
"plugin"
"plugin_test/iface"
"errors"
"fmt"
)
//go:generate go build -buildmode=plugin -o ./pg/test.so ./pg/test.go
func main(){
path := "pg/test.so"
plug, err := plugin.Open(path)
if err != nil {
panic(err)
}
sym, err := plug.Lookup("Greeter")
if err != nil {
panic(err)
}
var pg iface.IPlugin
pg, ok := sym.(iface.IPlugin)
if !ok {
panic(errors.New("error binding plugin to interface"))
}
fmt.Printf("You're now connected to: %s \n", pg.WhatsYourName())
pg.SayHello("user")
pg.SayGoodby("user")
}
O plug-in (armazenado em pg / test.go)
package main
import (
"fmt"
"plugin_test/iface"
)
type testpl struct {}
func(pl testpl) SayHello(s string){
fmt.Printf("Plugin says hello to %s \n", s)
}
func(pl testpl) SayGoodby(s string){
fmt.Printf("Plugin says goodby to %s \n", s)
}
func(pl testpl) WhatsYourName() string{
return "my name is Test-Plugin"
}
/* This function works */
func getPlugin() testpl{
return testpl{}
}
/* This function doesn't work */
func getPlugin() iface.IPlugin{
return testpl{}
}
/* This function also doesn't work */
func getPlugin() interface{}{
return testpl{}
}
var Greeter = getPlugin()
Eu tentei todosgetPlugin
funcionar por conta própria.
A função retornandotestpl
imprime a saída esperada:
You're now connected to: my name is Test-Plugin
Plugin says hello to user
Plugin says goodby to user
As outras funções terminam emsym.(iface.IPlugin)
panic: error binding plugin to interface
goroutine 1 [running]:
main.main()
/home/../../../main.go:27 +0x343
exit status 2
Alguém pode explicar por que isso não é possível? Não seria mais fácil criar um plug-in se não permitisse que você o construísse nesse caso?