How to Implement Plugin Architecture with Interfaces in Go

Define a Go interface for the plugin contract, implement it in a separate package, and load the compiled shared object at runtime using the `plugin` package.

How to Implement Plugin Architecture with Interfaces in Go

Define a Go interface for the plugin contract, implement it in a separate package, and load the compiled shared object at runtime using the plugin package.

// 1. Define the interface (host.go)
package main

type Plugin interface {
    Execute() string
}

// 2. Implement the interface in a plugin package (plugin_impl.go)
// Build with: go build -buildmode=plugin -o myplugin.so plugin_impl.go
package plugin_impl

func Execute() string { return "Hello from plugin" }

// 3. Load and use the plugin (main.go)
package main

import (
    "fmt"
    "plugin"
)

func main() {
    p, err := plugin.Open("myplugin.so")
    if err != nil { panic(err) }

    sym, err := p.Lookup("Execute")
    if err != nil { panic(err) }

    fn := sym.(func() string)
    fmt.Println(fn())
}