1

I sure hope this is something simple. When I grab information from within an if statement that is inside of a for loop it is not carried to outside of the for loop. I can print the information from within the if statement just fine and then lose it afterwards. Am I missing something? Coming from Python I have never experienced this before.

func main() {
    var neededinfo string
    for _, slice := range info_slices {
        // Get information out of slices
        if strings.Contains(slice, "indicator ") {
            neededinfo := string(ExeSH("echo '" + slice + "' | awk '{ print $4 }'"))
            neededinfo = neededinfo[1:len(neededinfo)-2]
            fmt.Println(neededinfo) // Returns my information
        }
    }
    fmt.Println(neededinfo) // Returns nothing
}
3
  • 2
    why are you initializing neededinfo again inside the loop? Commented Jul 9, 2014 at 23:51
  • I would remove the colon on the first line after your if statement and then see if that works, because var is technically initializing the variable. Commented Jul 9, 2014 at 23:52
  • @YasirG. You were spot on, the var was being overwritten Commented Jul 10, 2014 at 0:02

1 Answer 1

2

Most likely is the fact that you are overwriting the neededinfo variable

func main() {
    var neededinfo []string
    for _, slice := range info_slices {
        // Get information out of slices
        if strings.Contains(slice, "indicator ") {
            response := string(ExeSH("echo '" + slice + "' | awk '{ print $4 }'"))
            neededinfo = append(neededinfo, response[1:len(response)-2]
        }
    }
    fmt.Println(neededinfo) 
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.