Scope of variables in a program

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

1 Like
1 Like

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.

2 Likes

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,

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

1 Like

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

Thank you for the resource :slight_smile:

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.

1 Like

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