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
[80% OFF] Linux Foundation Coupon for November 2024
Looking for CKA Coupon and other Linux Foundation certifications coupons? We got you covered. With the latest Linux Foundation Coupon, you can
[40% OFF] Linux Foundation LFCA, LFCS & LFCT Exam Voucher Codes
Linux Foundation has announced up to a $284 discount on its Linux certification programs Linux Foundation Certified IT Associate (LFCA) and Linux
CKA Certification Study Guide (Certified Kubernetes Administrator)
This comprehensive CKA certification exam study guide covers all the important aspects of the Certified Kubernetes Administrator exam and useful resources. Passing