Variable Declaration Using var Block and := In golang
In this article, we will learn about how to declare multiple variables in a declaration block. And we can also use := to declare a variable.
As we see on lines 5-7 that every variable declaration is, we start with the var keyword and then provide variable name and then end with the type of the variable. We can also initialize variables using the assignment operator = and providing the value on the right hand side as follows,
var name string = "John"
The same thing has been done on lines 10-14. In this case, every variable declaration is not preceded by the var keyword rather all variables are inside a var block.
If we remove comments on lines 5-7, it will be not effective inside the main function due to re-declaration of the same variables. It is called shadowing. It means values assigned inside the main function will be effective.
We can also use var block outside any function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | package main import "fmt" //var name string //var age byte //var friends []string func main() { var ( name string age byte friends []string ) name = "John" age = 35 friends = []string{ "Mike", "Logan", "Peter", } fmt.Println(name, age, friends) } |
Now we have also commented var block on lines 10-14 and used operator := in place of = because we are declaring variables and not merely assigning the initial value. If we do not comment lines 10-14, declarations of the same variables using := operator will conflict.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | package main import "fmt" //var name string //var age byte //var friends []string func main() { /*var ( name string age byte friends []string )*/ name := "John" age := 35 friends := []string{ "Mike", "Logan", "Peter", } fmt.Println(name, age, friends) } |
Happy reading, see you soon.
Comments
Post a Comment