Skip to content

Commit

Permalink
make it generic
Browse files Browse the repository at this point in the history
  • Loading branch information
dogancanbakir committed Feb 15, 2025
1 parent d816ee9 commit 16062d8
Showing 1 changed file with 5 additions and 4 deletions.
9 changes: 5 additions & 4 deletions structs/structs.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,14 +43,15 @@ func Walk(s interface{}, callback CallbackFunc) {
// - input: the original struct.
// - includeFields: list of fields to include (if empty, includes all).
// - excludeFields: list of fields to exclude (processed after include).
func FilterStruct(input interface{}, includeFields, excludeFields []string) (interface{}, error) {
func FilterStruct[T any](input T, includeFields, excludeFields []string) (T, error) {
var zeroValue T
val := reflect.ValueOf(input)
if val.Kind() == reflect.Ptr {
val = val.Elem()
}

if val.Kind() != reflect.Struct {
return nil, errors.New("input must be a struct")
return zeroValue, errors.New("input must be a struct")
}

includeMap := make(map[string]bool)
Expand All @@ -76,13 +77,13 @@ func FilterStruct(input interface{}, includeFields, excludeFields []string) (int
}
}

return filteredStruct.Interface(), nil
return filteredStruct.Interface().(T), nil
}

// GetStructFields returns all the top-level field names from the given struct.
// - input: the original struct.
// Returns a slice of field names or an error if the input is not a struct.
func GetStructFields(input interface{}) ([]string, error) {
func GetStructFields[T any](input T) ([]string, error) {
val := reflect.ValueOf(input)
if val.Kind() == reflect.Ptr {
val = val.Elem()
Expand Down

0 comments on commit 16062d8

Please sign in to comment.