Scope of variables in a program


(Ashwin R) #1

I am currently reading a book called “The Go Programming language”. There is a section explaining the scope of variables. I am having a hard time understanding how the code in the link works. Please help me understand the same. Thanks in advance!!
Program can be found here: https://play.golang.org/p/X2INlbJK1JP


(Eric Lindblad) #2

Declaration scopes in Go


(Johan Dahl) #3

(Inanc Gumus) #4

Each curly brace { creates a new block (or you may say scope). Any variables declared in a block will belong to that block.

So,
x := "hello!" belongs to func main(). However, inner blocks, such as the for statement’s block can also see it.

x := x[i] inside the for statement belongs to that for statement. And, the func main() cannot see this new declaration.

And lastly, the if statement’s x := x + 'A' - 'a' belongs to that if statement. Neither the for statement nor the main func can see it. It’s because, it’s been declared in the innermost block. However, that if statement could see the previous x declaration however it declares a new x, so it can’t see it either.


(Kevin Maduro) #5

Ashwin, lets go line by line.
First of all, Johan gave a good call to post the code on this forum. At least, do it after you read his message.
We can explain efficiently and with more accuracy.

Going deeper in this code, it takes for every letter in the string and set it uppercase.
Imo I guess you’re talking about why the

x := "hello!"

and

x := x[i]

don’t give an error because you’re setting the value of x more than once.
My insights is that because this second x has another pointer (memory allocation) than the first variable x.
Being more technical
At least thats my point of view, if I mistake something someone feel free to correct me. But the eric’s answer is the bullseye shot.

Regards,


(Eric Lindblad) #6

My apologies if this is a bit off topic.

There’s a section “Lexically Scoped Variables” in the below.

https://nurmi-labs.blogspot.com/p/es-manual.html


(Ashwin R) #8

I’ll keep this in mind! Thanks for pointing it out.


(Ashwin R) #9

Thank you for the response. It’s clear now. :slight_smile:


(Ashwin R) #10

Thank you for the resource :slight_smile:


(Lucas B Bayer) #12

Ashwin,
Be careful because this code example you posted has something called variable shadowing that is discouraged in go.
This happens when an variable from an outer scope has the same name as a variable in an inner scope and it might cause confusion for someone who is not really familiar with the code.

Regards.