-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.go
55 lines (49 loc) · 1.25 KB
/
index.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
package query
import (
"fmt"
"reflect"
)
// IndexExtractor is the interface that wraps the ExtractByIndex method.
//
// ExtractByIndex extracts the value by index.
// It reports whether the index is found and returns the found value.
type IndexExtractor interface {
ExtractByIndex(index int) (interface{}, bool)
}
// Index represents an extractor to access the value by index.
type Index struct {
index int
}
// Extract extracts the value from v by index.
// It reports whether the index is found and returns the found value.
//
// If v implements the IndexExtractor interface, this method extracts by calling v.ExtractByIndex.
func (e *Index) Extract(v reflect.Value) (reflect.Value, bool) {
if v.IsValid() {
if i, ok := v.Interface().(IndexExtractor); ok {
x, ok := i.ExtractByIndex(e.index)
return reflect.ValueOf(x), ok
}
}
return e.extract(v)
}
func (e *Index) extract(v reflect.Value) (reflect.Value, bool) {
v = elem(v)
switch v.Kind() {
case reflect.Slice:
i := e.index
if v.Len() > i {
return v.Index(i), true
}
case reflect.Array:
i := e.index
if v.Len() > i {
return v.Index(i), true
}
}
return reflect.Value{}, false
}
// String returns e as string.
func (e *Index) String() string {
return fmt.Sprintf("[%d]", e.index)
}