-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathkey.go
62 lines (50 loc) · 1.42 KB
/
key.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package axon
import (
"fmt"
"reflect"
)
// Key the key type for the Injector.
type Key struct {
val any
isTypeKey bool
}
func (k Key) resolve(storage StorageGetter) containerProvider[any] {
return storage.Get(k)
}
func (k Key) String() string {
return fmt.Sprintf("%v", k.val)
}
func (k Key) IsEmpty() bool {
return k.val == nil
}
type KeyConstraint interface {
string
}
// NewKey creates a general purpose Key with any KeyConstraint value. Generally used with a string
//
// NewKey("my_key")
func NewKey[V KeyConstraint](val V) Key {
return Key{val: val}
}
// NewTypeKey returns a Key using the type V as well as the passed in value val.
func NewTypeKey[V any](val V) (Key, V) {
return newTypeKey[V](), val
}
// NewTypeKeyFactory rather than tying a particular type to a value like NewTypeKey, this func ties a type to a Factory.
func NewTypeKeyFactory[V any](val Factory) (Key, Factory) {
return newTypeKey[V](), val
}
// NewTypeKeyProvider rather than tying a particular type to a value like NewTypeKey, this func ties a type to a provider.
func NewTypeKeyProvider[V any](val V) (Key, *Provider[V]) {
return newTypeKey[V](), NewProvider(val)
}
// newTypeKey returns a Key based on the type of V.
func newTypeKey[V any]() Key {
return Key{
isTypeKey: true,
val: reflect.ValueOf(new(V)).Type().Elem().String(),
}
}
func newReflectKey(v reflect.Value) Key {
return Key{isTypeKey: true, val: v.Type().String()}
}