Why is targetPositions not being carried over to my inner loop here?

I haven’t tried to compile yet. I’m still getting things put together. Is this just VSCode being a pain? When I mouse-over, it says it isn’t defined. The text matches; no subtle differences in spelling.

Nevermind. Figured it out. The variable targetPositions only exists in a block that belongs to the function I call, similar to ownership in Rust. I didn’t understand that before.


targetPositions and ok are local to the if block scope. If you want those available elsewhere, declare them before the if.

targetPositions, ok := ...
if !ok {

// targetPositions is accessible here

See also A Tour of Go

Variables declared by the statement are only in scope until the end of the if .

I love the if x, ok := func () ; !ok {

As it saves lines of code. The need to declare ahead unfortunately makes it less useful.

“:=” is so convenient, but it is tricky. I wish the rule were if variable is not defined, create it.

Probably too late.