From 3606b33ee5a9deda9bbe589066980bfcc6c9104c Mon Sep 17 00:00:00 2001 From: qydysky Date: Fri, 19 Apr 2024 16:05:40 +0000 Subject: [PATCH] 1 --- component2/comp.go | 16 ++++++++-------- component2/comp_test.go | 4 ++-- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/component2/comp.go b/component2/comp.go index 93d632d..14da24d 100644 --- a/component2/comp.go +++ b/component2/comp.go @@ -14,27 +14,27 @@ var ( ErrGet = errors.New("ErrGet") ) -func PkgId() string { +func PkgId(varId ...string) string { if pc, _, _, ok := runtime.Caller(1); ok { - return strings.TrimSuffix(runtime.FuncForPC(pc).Name(), ".init") + return strings.Join(append([]string{strings.TrimSuffix(runtime.FuncForPC(pc).Name(), ".init")}, varId...), ".") } return "" } -func Register[TargetInterface any](pkgId string, _interface TargetInterface) error { - if pkgId == "" { +func Register[TargetInterface any](id string, _interface TargetInterface) error { + if id == "" { return ErrEmptyPkgId } - if _interfaceReg, ok := pkgInterfaceMap[pkgId]; ok && _interfaceReg != nil { + if _interfaceReg, ok := pkgInterfaceMap[id]; ok && _interfaceReg != nil { return ErrRegistered } else { - pkgInterfaceMap[pkgId] = _interface + pkgInterfaceMap[id] = _interface } return nil } -func Get[TargetInterface any](pkgId string, init ...func(TargetInterface) TargetInterface) (_interface TargetInterface) { - if tmp, ok := pkgInterfaceMap[pkgId].(TargetInterface); ok { +func Get[TargetInterface any](id string, init ...func(TargetInterface) TargetInterface) (_interface TargetInterface) { + if tmp, ok := pkgInterfaceMap[id].(TargetInterface); ok { for i := 0; i < len(init); i++ { tmp = init[i](tmp) } diff --git a/component2/comp_test.go b/component2/comp_test.go index 65f1fa2..8d69e8f 100644 --- a/component2/comp_test.go +++ b/component2/comp_test.go @@ -11,7 +11,7 @@ func (b B) AddOne(a int) int { } func init() { - if e := Register[a]("github.com/qydysky/part/component2", B{}); e != nil { + if e := Register[a]("github.com/qydysky/part/component2.aa", B{}); e != nil { panic(e) } aa = Get[a](pkgid) @@ -24,7 +24,7 @@ type a interface { // or var aa = Get[a](pkgid) var aa a -var pkgid = PkgId() +var pkgid = PkgId("aa") func Test(t *testing.T) { if aa.AddOne(1) != 2 { -- 2.39.2