Binding Plugins to Interfaces: A Conundrum
In Go, it's possible to create plugins that implement specific interfaces. However, there's a peculiar behaviour when returning an interface as a plugin symbol. Let's delve into this issue and explore a solution.
The Interface and Plugin:
We define an interface IPlugin with various methods and create a plugin containing a struct testpl that implements it. Initially, we have three different getPlugin functions:
The Problem with Lookup:
The solution lies in understanding how Plugin.Lookup() works. It returns a pointer to the symbol being looked up. In the case where the plugin exposes a variable (such as Greeter), the value stored in sym is a pointer to the variable.
The problem arises when we try to bind the plugin symbol to an interface. A value of a pointer type to an interface never satisfies any interfaces except the empty interface. Therefore, attempting to type-assert iface.IPlugin type from a value of type iface.IPlugin will always fail.
The Solution:
To resolve this issue, we need to either:
pgPtr, ok := sym.(*iface.IPlugin) if !ok { panic(errors.New("error binding plugin to interface")) } pg := *pgPtr
The above is the detailed content of Why Does Returning an Interface as a Go Plugin Symbol Fail, and How Can It Be Fixed?. For more information, please follow other related articles on the PHP Chinese website!