
GoLang Tutorial: Variable Tutorial For Beginners
- Last Updated On: December 23, 2017
- By: Scriptcrunch Editorial
A variable is an identifier for allocating memory to store a specific value.
Variable Declaration
Variable declaration in GO has the following syntax.
var <name of the variable> <variable type>
An example variable declaration is shown below.
package main import "fmt" func main() { var name string // variable declaration fmt.Println("my name", name) }
In the above code we declared the variable type string, however, we have assigned any value to it. So go automatically assigns the defaults value as empty. If the type is int, the default value will be zero.
Now let’s try to assign some value to few variable types.
package main import "fmt" func main() { var name string = "scriptcrunch" fmt.Println("my name", name) var num int = 1234 fmt.Println("Site No", num) }
Go Type Inference
One good thing about go is, you don’t have to declare the variable type like we did before. Go will automatically infer the variable type. For example
package main import "fmt" func main() { var name = "scriptcrunch" fmt.Println("my name", name) var num = 1234 fmt.Println("Site No", num) }
Multiple Variable Declaration
A single variable declaration can contain multiple variables.
package main import "fmt" func main() { var name, num = "scriptcrunch", 1234 fmt.Println("my name", name, "My number is", num) }
Multiple variables can be declared in the following way as well.
package main import "fmt" func main() { var ( name = "scriptcrunch" num = 1234 country string ranking float32 ) country = "United States" ranking = 13.456 fmt.Println("my name", name, "My number is", num) }
In the above example, we have four variables. Two variables have a value assigned during initialization while other two got initialized first with the variable type and later the values for assigned.
Shorthand Declaration
You can use the shorthand operator (:=) for assigning variables. Using shorthand you an initialize and assign variables in single line.
package main import "fmt" func main() { name := "scriptcrunch" num := 1234 country, code := "United States", 23.456 fmt.Println("my name", name, "My number is", num) fmt.Println("Country is", country, "code is ", num) }

Scriptcrunch Editorial
Other Interesting Blogs

Linux Foundation Coupon for November 2023
Hi Techies, I wanted to let you know about a pretty sweet deal with the Linux Foundation Coupon that is running now.


Best Black Friday Deals For Techies in 2023
In this blog, we have listed down all the best Black Friday deals and Cyber Monday deals for techies. This is the


CKA Exam Study Guide: Certified Kubernetes Administrator
Passing the cloud-native Certified Kubernetes Administrator (CKA) exam is not a cakewalk. To pass the CKA exam, you should have enough hands-on
