]> 127.0.0.1 Git - part/.git/commitdiff
1 v0.28.20240419161027
authorqydysky <qydysky@foxmail.com>
Fri, 19 Apr 2024 16:05:40 +0000 (16:05 +0000)
committerqydysky <qydysky@foxmail.com>
Fri, 19 Apr 2024 16:05:40 +0000 (16:05 +0000)
component2/comp.go
component2/comp_test.go

index 93d632dee6d74d32774fcc3f47c5f51af00c44f5..14da24d5d9a96a2e99490cc9c80a9c36b8f88950 100644 (file)
@@ -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)
                }
index 65f1fa24d529a4a5acb02b6224096dad4de603a0..8d69e8f30075a64c252109bbb3b317f43dc96e44 100644 (file)
@@ -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 {