go test -count 1 -timeout 10s -v -race github.com/qydysky/part/sql
go test -count 1 -timeout 10s -v -race github.com/qydysky/part/rpc
go test -count 1 -timeout 5s -v -race github.com/qydysky/part/component
+ go test -count 1 -timeout 5s -v -race github.com/qydysky/part/component2
go test -count 1 -timeout 15s -v -race github.com/qydysky/part/ctx
go test -count 1 -timeout 5s -v -race github.com/qydysky/part/slice
go test -count 1 -timeout 5s -v -race github.com/qydysky/part/bools
go test -count 1 -timeout 10s -v -race github.com/qydysky/part/sql
go test -count 1 -timeout 10s -v -race github.com/qydysky/part/rpc
go test -count 1 -timeout 5s -v -race github.com/qydysky/part/component
+ go test -count 1 -timeout 5s -v -race github.com/qydysky/part/component2
go test -count 1 -timeout 15s -v -race github.com/qydysky/part/ctx
go test -count 1 -timeout 5s -v -race github.com/qydysky/part/slice
go test -count 1 -timeout 5s -v -race github.com/qydysky/part/bools
go test -count 1 -timeout 10s -v -race github.com/qydysky/part/sql
go test -count 1 -timeout 10s -v -race github.com/qydysky/part/rpc
go test -count 1 -timeout 5s -v -race github.com/qydysky/part/component
+ go test -count 1 -timeout 5s -v -race github.com/qydysky/part/component2
go test -count 1 -timeout 15s -v -race github.com/qydysky/part/ctx
go test -count 1 -timeout 5s -v -race github.com/qydysky/part/slice
go test -count 1 -timeout 5s -v -race github.com/qydysky/part/bools
--- /dev/null
+package component2
+
+import (
+ "errors"
+ "runtime"
+ "strings"
+)
+
+var pkgInterfaceMap = make(map[string]any)
+
+var (
+ ErrEmptyPkgId = errors.New("ErrEmptyPkgId")
+ ErrRegistered = errors.New("ErrRegistered")
+)
+
+func PkgId() string {
+ if pc, _, _, ok := runtime.Caller(1); ok {
+ return strings.TrimSuffix(runtime.FuncForPC(pc).Name(), ".init")
+ }
+ return ""
+}
+
+func Register[TargetInterface any](pkgId string, _interface TargetInterface) error {
+ if pkgId == "" {
+ return ErrEmptyPkgId
+ }
+ if _interfaceReg, ok := pkgInterfaceMap[pkgId]; ok && _interfaceReg != nil {
+ return ErrRegistered
+ } else {
+ pkgInterfaceMap[pkgId] = _interface
+ }
+ return nil
+}
+
+func Get[TargetInterface any](pkgId string, defaultInterface ...TargetInterface) (_interface TargetInterface) {
+ if tmp, ok := pkgInterfaceMap[pkgId].(TargetInterface); ok {
+ return tmp
+ }
+ if len(defaultInterface) > 0 {
+ return defaultInterface[0]
+ }
+ return
+}
--- /dev/null
+package component2
+
+import (
+ "testing"
+)
+
+type B struct{}
+
+func (b B) AddOne(a int) int {
+ return a + 1
+}
+
+func init() {
+ if e := Register[a]("github.com/qydysky/part/component2", B{}); e != nil {
+ panic(e)
+ }
+ aa = Get[a](pkgid)
+}
+
+type a interface {
+ AddOne(int) int
+}
+
+// or var aa = Get[a](pkgid)
+var aa a
+
+var pkgid = PkgId()
+
+func Test(t *testing.T) {
+ if aa.AddOne(1) != 2 {
+ t.Fatal()
+ }
+}