Easily understand Go variables with visual examples.
Go defines the variables as they read. Go is explicit andĀ simple.
Instead of doing the arithmetic of Clockwise/Spiral Rule magic to read a C declaration, Go uses a simpler approach for us humans, not for aliens (I used to Cās declaration syntax after some time back then but that doesnāt mean we canāt make things better as inĀ Go).
ā CāsĀ version:
ā GoāsĀ version:
Humanized
A variable has a type, value and an address, as seen below. Variables are used when you need to store data somewhere to use it again for later operations in yourĀ code.
Go is a statically-typed language. That means, every variable should have a type and all types are different from eachĀ other.
Type ā What kind of information can be stored inside the variable.
Value ā The stored value inside the variable.
Address ā Where the variable can be found in computerĀ memory.
Simply put, variables let us store data somewhere. Programming is all about transforming one form of data to another. Without variables, there would be only static-data in our programs that we canāt change. The static-variables would be baked in our static programs.
Variables let us do dynamic things, such as getting user feedback and store it into a variable, re-using the same value again, like in math PI number. We donāt have to type the values again and again thanks to variables.
If you would go into the machine-code level, which is the language that microprocessors understand (and some aliens), you would see that, there are many variable storage mechanisms that transform data from one form to another. So, basically, thereās a hardware-level support for variables in our computers.
Before I show you how you can declare a variable, itās better to talk about zero-values briefly which has a good importance inĀ Go.
Left side gets right sideās values if not initialized.
If a variable is just declared and no value assigned to it, then Go will assign it a zero-value depending on the type of the variable. You can see which types get which zero-values by looking at the imageĀ above.
This can come confusing to you at first, however, the rest of the notations except the first one are more like helper notations.
- The first one is the long declaration which uses the varĀ keyword.
- The second one is the short declaration which guesses the variableās type automatically.
- The third one is the multiple variable declaration, itās like a mix of long and short declarations for multiple variables.
- And the last one is one-line multiple short declaration.
Declares a variable named ageOfUniverse with a type of declare: var keyword declares a new variable.
Declare ā var keyword declares a new variable.
Name ā The variableās name is ageOfUniverse.This can be anything (including unicodes like Ļ, ā, ā«, but not this:Ā š±_)._
Type ā Which kind of data we can store inside of the variable.Here, we use int, because, we want to measure the age of the universe, maybe in years, approximately.
When you just declare a variable by long declaration without assigning a variable to it, its value will be a zero-value. Zero-values are the defaults values inĀ Go.
Declares a variable named ageOfUniverse and stores a value of 14 billions in the variable and guesses its type automatically.
Name ā The name of the variable which is ageOfUniverse
Declare & Assign āĀ := is a special type of operator which declares and assigns a value to a variable.
Value ā T_he data we want to store into the variable._
The variable is declared and its value and type are assigned all together. You can assign any value that Go permits. Cool, yeah? Go can guess the type of the variable for you. This is called as type-inferring and this type of declaration is called as short variable declaration or simply: short declaration.
When you use short declaration, Go will not use a zero-value assignment, obviously. Because, you directly assign a value to the variable, this will be its initial value. Though, you can assign a zero-value manually, as well. For example, you can assign 0 to an integer while you were still using the short-declaration (0 is a zero-value for integers).
By the way, 14e9 means, 14 billions. Itās called scientific-notation. Its default type is float64. āeā puts 9 zeros afterĀ 14.
Declares multiple variables which have different types and values in the same statement.
This is kind of a mix of the long and the short variable declaration notations. var keyword declares a group of variables when used within paranthesis.
The first line, ageOfUniverse int, is like a long declaration. Just declares a variable with a type you want and assigns it a zero-value automatically.
The second line, is new to you, itās called, multiple-variable declaration. Just as with short declaration, it declares and assigns to the variables. Variable and value names are separated withĀ commas.
The number of items on the left-hand side (which is: livablePlanets, ageOfEarth) should match to the number of items on the right-hand side (which is: 1, 4.5e9). No need to type, short-declaration operator here,Ā ā__:=ā.
The third line is like the second line, however, it just declares coolLang variable and assigns it a string: go. Notice that, when using it with one variable, thereās no need to use aĀ commas.
Declares two variables of type float64 and string; and assigns 14 billions to the first and āgoā to the second variable.
This is a simpler version of multiple-variable declaration which uses the short declaration. You just separate the variables and the values by commas. The number of variables and the values shouldĀ match.
Also called assigning data and = operator is used when assigning data to a variable. The variable should have been declared before and the data type should be the same with the variableās declared data type. The variable will hold the new data that youĀ set.
However, when you want to assign wrong type of data to a variable, Go compiler will warn you and fail to compile. For example, you canāt assign a string to a variable which has a type ofĀ integer.
Use long declaration, when you canāt know what data to store inside of the variable. Use short declaration, wherever you know what to store inside the variable.
Use multiple declarations, wellā¦, when you want to define multiple variables together. Also, use multiple declarations when you want to give a hint to other coders who read your code that you want to group this type of variables together. See this for otherĀ details.
By the way, you canāt use short declarations outside of functions including main function. Or: you will meet with this error: āsyntax error: non-declaration statement outside functionĀ bodyā.
When we declare an integer variable, Go reserves a 4-bytes of storage space in the memory for the variable. When the data doesnāt fit into the variable, Go compiler will warn you about that thereās an overflow and terminate.
However, int is a floppy type. Data it can store can change depending on the compilation. When compiling for a 32-bit architecture, it can hold 4-bytes, and in a 64-bit architecture, it can holdĀ 8-bytes.
So, we canāt just simply store the age of the universe in an int variable. We should have used uint64 instead, explicitly. Because, an int canāt store ~14 billions of years, it can only store up to ~4 billions of years on 32-bit machines. Or it will overflow, but for a 64-bit machine, compilation willĀ work.
You canāt store 14 billions in a 4-bytesĀ storage.
Note: Universe was an infinitely small and dense dot once upon a ātimeā (Or wasnāt it? Ethan Siegel?), however that doesnāt mean that we can do the same with Go!Ā š
Try it yourself.
Play with it: Example shows you how many bytes the ageOfUniverse variable canĀ store.
Incorrect code. Run it to see yourself.
Correct-ish code. RunĀ it.
When you create a new variable, its life is limited in the scope which it was defined. We will talk about the scopes in much later tutorials. However, itās good to know for now that, one of the important scopes that I want to tell you for now is that there is a package-level scope, and function-level scope.
When we declare a new variable inside of a function, it can only be used inside that function (unless we returned it from the function or write it to somewhere else). And, when we declare a new variable in the package scope, it can be seen and used by all the other package members unless we exported it to other packages. To define a variable in the package scope, you just need to use long declaration, you canāt use short declaration for package scope variables.
To export a variable to another packages we need to type the first letter of the variableās name with an uppercase letter. However, I donāt recommend to expose your package variables to the outside world as much as you can. Even, it may be harmful to expose variables to the package. There are other ways to do that. You may read my post about encapsulation and packages, also read the part: āHide almost everythingā in my anotherĀ post.
OK, folks, thatās all for now. Thanks forĀ reading!
ā¤ļø Please support me: Follow my publication and Add claps to my post!ā¤ļø Share it on social media, spread theĀ love.
š¦ Iām mostly tweeting about Go,you can follow me on twitter: @inancgumus.
You will receive notifications about my new posts and upcoming online Go course (every Wednesday).
Click on the image to subscribe to āLearn Go Programmingā email list! ThankĀ you!
Originally published at blog.learngoprogramming.com on October 4,Ā 2017.