I've got a three component for loop that iterates over a Policies struct, which holds a list of Policy types, which is also a struct. However, in the for loop, the 'i ' is highlighted and apparently unreachable. I'm not sure why? Because when I run the application, it does actually execute the c.sendResultDialog function, so it is reachable, but I don't know why this error is showing up.
for i := 0; i < len(policies.Policies); i {
if strings.ToLower(c.name) == strings.ToLower(policies.Policies[i].PolicyName) || strings.ToLower(c.name) == strings.ToLower(policies.Policies[i].PolicyId) {
c.sendResultDialog(TestFoundPolicy, c.name, policies.Policies[i].PolicyId, policies.Policies[i].PolicyDescription)
return true
} else {
c.sendResultDialog(PolicyNotFound, c.name)
return false
}
}
CodePudding user response:
Since, you call return inside the for loop, you are not iterating over all the slice values. You would probably do this
policy_found := false
for i := 0; i < len(policies.Policies); i {
if strings.ToLower(c.name) == strings.ToLower(policies.Policies[i].PolicyName) || strings.ToLower(c.name) == strings.ToLower(policies.Policies[i].PolicyId) {
c.sendResultDialog(TestFoundPolicy, c.name, policies.Policies[i].PolicyId, policies.Policies[i].PolicyDescription)
policy_found = true
}
}
if !policy_found {
c.sendResultDialog(PolicyNotFound, c.name)
policy_found = false
}
return policy_found
this should fix your bug
CodePudding user response:
This is hard to tell without a full example (no idea what sendResultDialog is doing). But the error is likely due to the fact that you're returning from within a loop, you can try something like this instead:
policyFound := false
for i := 0; i < len(policies.Policies); i {
if strings.ToLower(c.name) == strings.ToLower(policies.Policies[i].PolicyName) || strings.ToLower(c.name) == strings.ToLower(policies.Policies[i].PolicyId) {
c.sendResultDialog(TestFoundPolicy, c.name, policies.Policies[i].PolicyId, policies.Policies[i].PolicyDescription)
policyFound = true
break // remove this if you want to call sendResultDialog for all entries and not just the first one
}
}
if !policyFound {
c.sendResultDialog(PolicyNotFound, c.name)
}
return policyFound