I am attempting to iterate over a struct which looks like this:
type Cpe23 struct {
Part string
Vendor string
Product string
Version Version
Update string
Edition string
SwEdition string
TargetSw string
TargetHw string
Language string
Other string
}
All I am looking to do is concatenate the values into a string and print the results. The issue comes from the fact that the Version
struct is obviously not a string, so it needs to be treated differently. Here is the Version
struct:
type Version struct {
Original string
Semver *semver.Version
Valid bool
}
In the case of the Version
field, I want to pull out the Original
value and add that to the resulting string. Here is the code that I have tried based on what I was able to google. I know I am close but I just can't quite seem to figure out reflection/type assertion...
func FormCpeString(component Cpe23) string {
cpeString := "cpe:2.3"
v := reflect.ValueOf(component)
for i := 0; i < v.NumField(); i++ {
f := v.Field(i)
// If an empty field, replace with asterisk (all)
if f.Interface() == "" {
cpeString += ":*"
} else if f.Type().Name() == "Version"{
t := f.(Version)
cpeString += fmt.Sprintf(":%s", t.Original)
} else {
// do some validation checks here TODO
cpeString += fmt.Sprintf(":%s", v.Field(i).Interface())
}
}
return cpeString
}
The error I am getting is ./main.go:433:10: invalid type assertion: f.(Version) (non-interface type reflect.Value on left)
I understand what this error is saying, I just can't seem to find the right syntax to allow me to pull fields out of the Version
. Any guidance would be appreciated.
Aucun commentaire:
Enregistrer un commentaire