#Variable declared and not used

6 messages · Page 1 of 1 (latest)

hazy pulsar
#
res := make([]int, len(nums))
    for i := 0; i < len(nums); i++ {
        if i == 0 {
            prefix_val := 1
        } else {
            prefix_val := prefix[i-1]
        }
        if i == len(nums) - 1 {
            postfix_val := 1
        } else {
            postfix_val := postfix[i+1]
        }
        res[i] = prefix_val * postfix_val
    }

Error:

Line 25: Char 13: declared and not used: prefix_val (solution.go)
Line 27: Char 13: declared and not used: prefix_val (solution.go)
Line 30: Char 13: declared and not used: postfix_val (solution.go)
Line 32: Char 13: declared and not used: postfix_val (solution.go)
Line 34: Char 18: undefined: prefix_val (solution.go)
Line 34: Char 31: undefined: postfix_val (solution.go)

Why does the compiler say I have not used prefix_val and postfix_val when you can clearly see it being used in the last line? It also says that both the before mentioned variables are undefined which are clearly defined above.

#

I was able to solve it by adding var prefix_val int and var postfix_val int above the if/else statement. But why does this happen?

random hound
#

Variables declared inside if statements are scoped only within them.
you have to do this

res := make([]int, len(nums))
for i := 0; i < len(nums); i++ {
    var prefixVal, postfixVal int

    if i == 0 {
        prefixVal = 1
    } else {
        prefixVal = prefix[i-1]
    }
    if i == len(nums)-1 {
        postfixVal = 1
    } else {
        postfixVal = postfix[i+1]
    }
    res[i] = prefixVal * postfixVal
}
hazy pulsar
#

ahh I get it now

#

forgot some fundamentals

#

thank you!