-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathextract.go
52 lines (41 loc) · 1.49 KB
/
extract.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
package inject
import (
"fmt"
"reflect"
)
// ExtractByType resolves a pointer into a value by finding exactly one defined pointer with the specified type
func ExtractByType(g Graph, ptr interface{}) reflect.Value {
ptrType := reflect.TypeOf(ptr)
if ptrType.Kind() != reflect.Ptr {
panic(fmt.Sprintf("ptr (%v) is not a pointer", ptrType))
}
targetType := reflect.ValueOf(ptr).Elem().Type()
values := g.ResolveByType(targetType)
if len(values) > 1 {
panic(fmt.Sprintf("more than one defined pointer matches the specified type (%v)", ptr))
} else if len(values) == 0 {
panic(fmt.Sprintf("no defined pointer matches the specified type (%v)", ptr))
}
value := values[0]
// update the ptr value
reflect.ValueOf(ptr).Elem().Set(value)
return value
}
// ExtractAssignable resolves a pointer into a value by finding exactly one defined pointer with an assignable type
func ExtractAssignable(g Graph, ptr interface{}) reflect.Value {
ptrType := reflect.TypeOf(ptr)
if ptrType.Kind() != reflect.Ptr {
panic(fmt.Sprintf("ptr (%v) is not a pointer", ptrType))
}
targetType := reflect.ValueOf(ptr).Elem().Type()
values := g.ResolveByAssignableType(targetType)
if len(values) > 1 {
panic(fmt.Sprintf("more than one defined pointer is assignable to the specified type (%v)", ptr))
} else if len(values) == 0 {
panic(fmt.Sprintf("no defined pointer is assignable to the specified type (%v)", ptr))
}
value := values[0]
// update the ptr value
reflect.ValueOf(ptr).Elem().Set(value)
return value
}