Basics of Go: Variables and it's Magic

Avatar of Rakesh Mothukuri

Rakesh Mothukuri

| Reading Time : 1 minute

Avatar of Rakesh Mothukuri Avatar of Rakesh Mothukuri Avatar of Rakesh Mothukuri Avatar of Rakesh Mothukuri

[TOC]

There are many ways to assign a variable in Go. Here below are some of those which I have encountered till date.

**Syntax:** var i int

package main

import "fmt"

func main() {
	var i int
	fmt.Println(i)
}

The var statement can be at either package or function level and it declares a list of variables the type is last.

If an initializer is present, the type can be omitted and the variable will assume the type of the initializer. Example :

package main

import "fmt"

var i, j int = 1, 2

func main() {
	var c, python, java = true, false, "no!"
	fmt.Println(i, j, c, python, java)
}

Interesting syntax :=

Inside a function, the := short assignment statement can be used in place of a var declaration with implicit type.

Example:

package main

import "fmt"

func main() {

	var k int = 3
	//:= is short assignment can be used in place of var declaration with implicit type.
	l := 3
	fmt.Println(k, l)
}

Output :
k is 3
l is 3

My Image