First Go Lesson: Variable declaration and passing by reference

I beginning my journey with Go by taking the Go Fundamentals Pluralsight course. It’s great so far.

I would love to share some interesting stuff I see about the Go language. Also, it helps me not to forget the nuances of the language and reassures me that I understand how things work.

Variable declaration

Declaring variables in Go is quite interesting. The var keyword is only used to declare variables that are package scoped. Package scope means that the variable can be used by any function inside the package (think module in Node world or namespace in C#). I’ve never really thought of that kind of scoping before. I’ll have to dig into that more as I continue to learn.

The interesting thing is that if you are declaring and instantiating a variable in Go inside a function, you use the “:=” syntax (colon and equals) like this:

variable-assignment

Also, I find it interesting that Go will not compile if you declare a variable and not use it. That is a great way of making sure there is no waste in your programs.

Passing parameters by reference

Go has another interesting “feature”. It always passes function parameters by value (for anything that is not a slice). This means that a copy of the value is created and then passed in. Any changes made to the value of that parameter while inside the function will not change the original. So if you declare a variable in one function, pass it into another function that manipulates the value, then use that value after the second function is called, you will get the original value. Let’s say the code looks like this:

func_pass_parameter

The output when this code is run is the following:

Go_not_reference

Notice how the course name does not change. I’m used to languages like C# where whether or not a parameter is passed by value is dependent on the type of the variable. For instance, strings are always passed by reference and ints are always passed by value. Here in this example, we see that even strings are always copied when passed into functions in Go. You have to use pointers in Go if you want to pass by reference and change the original variable. Notice the changes in the following code:

Refrerences

Now when you run the code…

reference_output

The original value is changed. Cool stuff.

If you are interested in learning more, please check out Nigel Poulton’s Pluralsight course: Go Fundamentals. These code samples came from his course. It’s great.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s