mirror of
https://github.com/c9s/bbgo.git
synced 2024-11-10 09:11:55 +00:00
dynamic: add IterateFields
This commit is contained in:
parent
b3e04a68da
commit
825022715d
|
@ -10,6 +10,44 @@ type StructFieldIterator func(tag string, ft reflect.StructField, fv reflect.Val
|
||||||
|
|
||||||
var ErrCanNotIterateNilPointer = errors.New("can not iterate struct on a nil pointer")
|
var ErrCanNotIterateNilPointer = errors.New("can not iterate struct on a nil pointer")
|
||||||
|
|
||||||
|
func IterateFields(obj interface{}, cb func(ft reflect.StructField, fv reflect.Value) error) error {
|
||||||
|
sv := reflect.ValueOf(obj)
|
||||||
|
st := reflect.TypeOf(obj)
|
||||||
|
|
||||||
|
if st.Kind() != reflect.Ptr {
|
||||||
|
return fmt.Errorf("f should be a pointer of a struct, %s given", st)
|
||||||
|
}
|
||||||
|
|
||||||
|
// for pointer, check if it's nil
|
||||||
|
if sv.IsNil() {
|
||||||
|
return ErrCanNotIterateNilPointer
|
||||||
|
}
|
||||||
|
|
||||||
|
// solve the reference
|
||||||
|
st = st.Elem()
|
||||||
|
sv = sv.Elem()
|
||||||
|
|
||||||
|
if st.Kind() != reflect.Struct {
|
||||||
|
return fmt.Errorf("f should be a struct, %s given", st)
|
||||||
|
}
|
||||||
|
|
||||||
|
for i := 0; i < sv.NumField(); i++ {
|
||||||
|
fv := sv.Field(i)
|
||||||
|
ft := st.Field(i)
|
||||||
|
|
||||||
|
// skip unexported fields
|
||||||
|
if !st.Field(i).IsExported() {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := cb(ft, fv) ; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
func IterateFieldsByTag(obj interface{}, tagName string, cb StructFieldIterator) error {
|
func IterateFieldsByTag(obj interface{}, tagName string, cb StructFieldIterator) error {
|
||||||
sv := reflect.ValueOf(obj)
|
sv := reflect.ValueOf(obj)
|
||||||
st := reflect.TypeOf(obj)
|
st := reflect.TypeOf(obj)
|
||||||
|
|
25
pkg/dynamic/iterate_test.go
Normal file
25
pkg/dynamic/iterate_test.go
Normal file
|
@ -0,0 +1,25 @@
|
||||||
|
package dynamic
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"reflect"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestIterateFields(t *testing.T) {
|
||||||
|
var a = struct {
|
||||||
|
A int
|
||||||
|
B float64
|
||||||
|
C *os.File
|
||||||
|
}{}
|
||||||
|
|
||||||
|
cnt := 0
|
||||||
|
err := IterateFields(&a, func(ft reflect.StructField, fv reflect.Value) error {
|
||||||
|
cnt++
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
assert.NoError(t, err)
|
||||||
|
assert.Equal(t, 3, cnt)
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user