github.com/dolthub/dolt/go@v0.40.5-0.20240520175717-68db7794bea6/libraries/utils/structwalk/walk.go (about) 1 // Copyright 2024 Dolthub, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package structwalk 16 17 import ( 18 "reflect" 19 ) 20 21 func Walk(v any, f func(sf reflect.StructField, depth int) error) error { 22 return walkStruct(v, 0, f) 23 } 24 25 func walkStruct(v any, depth int, f func(sf reflect.StructField, depth int) error) error { 26 t := reflect.TypeOf(v) 27 if t.Kind() == reflect.Ptr { 28 t = t.Elem() 29 } 30 31 return walkFields(t, depth, f) 32 } 33 34 func walkFields(t reflect.Type, depth int, f func(sf reflect.StructField, depth int) error) error { 35 for i := 0; i < t.NumField(); i++ { 36 field := t.Field(i) 37 err := processField(field, depth, f) 38 if err != nil { 39 return err 40 } 41 } 42 43 return nil 44 } 45 46 func processField(field reflect.StructField, depth int, f func(sf reflect.StructField, depth int) error) error { 47 if err := f(field, depth); err != nil { 48 return err 49 } 50 51 if field.Type.Kind() == reflect.Ptr || field.Type.Kind() == reflect.Slice { 52 if field.Type.Elem().Kind() == reflect.Struct { 53 t := field.Type.Elem() 54 if err := walkFields(t, depth+1, f); err != nil { 55 return err 56 } 57 } 58 } else if field.Type.Kind() == reflect.Struct { 59 if err := walkFields(field.Type, depth+1, f); err != nil { 60 return err 61 } 62 } 63 64 return nil 65 }