I've begun learning Go, and I ran into a strange bug, and an even stranger fix for it working on a HackerRack problem:
func countingValleys(steps int32, path string) int32 {
// Write your code here
var level int32 = 0
var valleys int32 = 0
// The below declaration was throwing the initial error
insideValley := false
for _, char := range path {
fmt.Println(insideValley)
if string(char) == "U" {
if level == -1 {
insideValley = false
valleys += 1
}
level += 1
} else if string(char) == "D"{
if level == 0 {
insideValley = true
}
level -= 1
}
}
return valleys
}
The compiler was complaining that insideValley is declared by not used, both on HR and the Go playground. I added the fmt.Println call immediately inside of the for loop to debug, suspecting it to be a scope error, and the error went away AND my code passed all tests for the challenge, leaving me wondering:
Why was the error being thrown in the first place? My current understanding of variable scope in Go is that when declared in a function like this, it will be available to all blocks contained within the function.
Why did adding the
fmt.Printlnof that var fix the error? I would have assumed with my current understanding that IF you can only nest X amount of blocks before variables in enclosing blocks become out of scope, the only fix for it would involve pointers.