All checks were successful
continuous-integration/drone/push Build is passing
60 lines
1.4 KiB
Go
60 lines
1.4 KiB
Go
package utils
|
|
|
|
import (
|
|
"fmt"
|
|
"log"
|
|
"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)
|
|
|
|
log.Printf("PrintStructContents field '%s' (%T)\n", field, fieldType)
|
|
|
|
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:
|
|
log.Printf("%v\n", field.Interface())
|
|
result.WriteString(fmt.Sprintf("%v\n", field.Interface()))
|
|
}
|
|
}
|
|
|
|
return result.String()
|
|
}
|
|
|
|
type Identifiable interface {
|
|
GetId() int
|
|
}
|
|
|
|
// AppendIfNotExists requires a struct to implement the GetId() method
|
|
// 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)
|
|
}
|