How to ignore the golang variable scope and handle variables defined in a for or if outside of a for or if

My code

package main

import "fmt"

func main(){
  for(
    a := "2"
  )
  fmt.Println(a)
}

Println" with “fmt.Println” on “for” and “a” defined “within”, I get “undefined”.
Now I want to display two defined a’s
I don’t know of any solution to this problem, to my knowledge.

Can you wrap your code in three backticks (```) like this:

```
code here
```

And paste it again? I’m not certain of what you’re trying to do. Based on the title of your post mentioning scope, I think you might mean something like this:

package main

import (
	"fmt"
)

func main() {
	{
		a := 123
	}
	fmt.Println(a)
}

(playground)

Which doesn’t work because a is defined in an inner scope and isn’t defined in the outer scope where you’re using fmt.Println.

To directly answer that question, how to ignore the variable scope: You can’t.

As for workarounds, you could do this:

func main() {
  var a int
  {
    a = 123
  }
  fmt.Println(a)
}

If this is what you meant, I want to note that scopes are not a bad thing. If you want variables to be accessible across scopes, move them up to a common scope, or come up with some way to pass the information (e.g. a function call, embedding as a field, slice index, map key, etc. in some other variable that does exist in an outer scope).

2 Likes

Thanks for telling me! And I wrapped the code part with a ````.And I didn’t know enough about it.…Great tips!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.