try doing magic with generics
All checks were successful
continuous-integration/drone/push Build is passing
All checks were successful
continuous-integration/drone/push Build is passing
This commit is contained in:
55
utils/structOperations.go
Normal file
55
utils/structOperations.go
Normal file
@@ -0,0 +1,55 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func PrintStructContents(s interface{}, indentLevel int) string {
|
||||
var result strings.Builder
|
||||
|
||||
val := reflect.ValueOf(s)
|
||||
|
||||
if val.Kind() == reflect.Ptr {
|
||||
val = val.Elem()
|
||||
}
|
||||
|
||||
typ := val.Type()
|
||||
|
||||
for i := 0; i < val.NumField(); i++ {
|
||||
field := val.Field(i)
|
||||
fieldType := typ.Field(i)
|
||||
|
||||
indent := strings.Repeat("\t", indentLevel)
|
||||
result.WriteString(fmt.Sprintf("%s%s: ", indent, fieldType.Name))
|
||||
|
||||
switch field.Kind() {
|
||||
case reflect.Struct:
|
||||
result.WriteString("\n")
|
||||
result.WriteString(PrintStructContents(field.Interface(), indentLevel+1))
|
||||
default:
|
||||
result.WriteString(fmt.Sprintf("%v\n", field.Interface()))
|
||||
}
|
||||
}
|
||||
|
||||
return result.String()
|
||||
}
|
||||
|
||||
type Identifiable interface {
|
||||
GetId() int
|
||||
}
|
||||
|
||||
// AppendIfNotExists requires a struct to implement the GetId() function
|
||||
// Then we can use this function to avoid creating duplicate entries in the slice
|
||||
func AppendIfNotExists[T Identifiable](slice []T, element T) []T {
|
||||
for _, existingElement := range slice {
|
||||
if existingElement.GetId() == element.GetId() {
|
||||
// Element with the same Id already exists, don't append
|
||||
return slice
|
||||
}
|
||||
}
|
||||
|
||||
// Element with the same Id does not exist, append the new element
|
||||
return append(slice, element)
|
||||
}
|
Reference in New Issue
Block a user