What is the use of curly brackets in this gist

1,887 views
Skip to first unread message

GoNutter

unread,
Mar 14, 2016, 10:52:07 AM3/14/16
to golang-nuts
Hi,

I have been looking at a Gist and there is some usage of curly brackets that I have not encountered before where blocks of code are surrounded with curly brackets. 


What is the interpretation of this usage? What is it called so I can find reference on it.

Many thanks

chris dollin

unread,
Mar 14, 2016, 11:00:44 AM3/14/16
to GoNutter, golang-nuts
On 14 March 2016 at 14:52, GoNutter <anewex...@gmail.com> wrote:
> Hi,
>
> I have been looking at a Gist and there is some usage of curly brackets that
> I have not encountered before where blocks of code are surrounded with curly
> brackets.

Nested scopes. Names declared within the {} aren't visible outside.

Chris

--
Chris "allusive" Dollin

pierre...@gmail.com

unread,
Mar 14, 2016, 11:00:50 AM3/14/16
to golang-nuts
Hello,

They are used to create new blocks, see https://golang.org/ref/spec#Blocks.

Within a block you can create new variables within the block scope, allowing to use the same identifier multiple times as long as they are in different blocks.
It is convenient to use in a redundant manner: just copy and paste the same code over and over only changing some values. Useful to write tests for instance without having to create a new function every time.

Val

unread,
Mar 14, 2016, 11:03:20 AM3/14/16
to golang-nuts
I think they're called "Blocks" : https://golang.org/ref/spec#Blocks

In the main func of your gist, each block has its own scope not leaking into each other. That way, they can all declare variable "original" and "translated" independently.

Konstantin Khomoutov

unread,
Mar 14, 2016, 11:11:12 AM3/14/16
to GoNutter, golang-nuts
If you're referring to stuff in main(), like [2], these are, well,
"blocks" [3]. A block creates a new scope for variables declared in it.
This can be used to 1) making sure the variables declared and used in a
block seize to exist when the block is left; 2) declare the same-named
variable in several (consequtive) blocks -- having a different type in
each of them.

This feature is not Go specific and exist, say, in C.
It's often overlooked in tutorial material and hence may take a
non-seasoned programmer by surprise.

2. https://gist.github.com/hvoecking/10772475#file-translate-go-L100
3. https://golang.org/ref/spec#Blocks

GoNutter

unread,
Mar 14, 2016, 11:37:21 AM3/14/16
to golang-nuts, pierre...@gmail.com
Great, thanks for the help.
Reply all
Reply to author
Forward
0 new messages