golang variable tutorial

GoLang Tutorial: Variable Tutorial For Beginners

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)
}

Try in Go Playground

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)

}

Try in Go Playground

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)

}

 

golang variable tutorial

Other Interesting Blogs

Leave a Comment

0 Shares
Share via
Copy link