Shorthand Declaration Of Variables.¶
Objective¶
Learn how to declare variables using the shorthand method.
Declaration¶
Go ships with a smart compiler, it can detect the data type and automatically assign it to variables, using short declaration is very widely used in Go, with this method you can create variables on the fly, no need for prior declaration.
General syntax
1 |
|
It is also called as inference type declaration, meaning that the variable type is "inferred" from the value. This method offers various benefits such as compiler can choose the right data type and much more which we will explore as we write more code.
Structure¶
Navigate to our code folder
1 |
|
For our program create a new folder '06_shorthand_declaration'
1 |
|
And lets create a file 'shorthand_declaration.go' in it, finally the structure would look like this:
1 |
|
Code¶
Shorthand Declaration
1 package main
2
3 import "fmt"
4 func main() {
5 // declaring integer
6 num := 12
7 fmt.Printf("The type of variable 'num' is: %T.\n", num)
8
9 // declaring float
10 decimal := 15.45
11 fmt.Printf("The type of variable 'decimal' is: %T.\n", decimal)
12
13 // declaring string
14 name := "Octallium"
15 fmt.Printf("The type of variable 'name' is : %T.\n", name)
16 }
Code Review¶
On line 6, 10 & 14 we declare a new variable
1 2 3 |
|
To check the data type we use a special format output function
1 |
|
Note, in the earlier examples we had used
1 |
|
On line 7, 11 & 15, we print out the data type, to check the data type we use a special character "%T", which acts as a placeholder and represent the data "Type", it is followed by the variable name.
1 2 3 |
|
If you don't understand the print statements, no worries, we will be having a dedicated section on formatting output, for now type everything as in the code above and make sure it runs.
Run Code¶
Open your terminal and navigate to our folder
1 |
|
Once in the folder type the following command
1 |
|
Output¶
Output
1 2 3 |
|
Github¶
Just in case you have some errors with your code, you can check out the code at github repo
Golang Playground¶
You can also run the code at playground
Next¶
In the next chapter we will see about if/else condition, don't worry if its becoming too geeky, keep up with the code and in no time you will get the hang of it.