AppDividend
Latest Code Tutorials

Golang Variables Example | Variables in Go

0

Golang variables are explicitly declared and used by the compiler to check the type-correctness of function calls. Variable is the name given to the memory location to store the value of a particular type. There are numerous syntaxes to declare variables in go. A variable is a storage location with a particular type and an associated name.

Golang Variables

Go variable is a placeholder of the information which can be changed at runtime. The variable allows us to retrieve and manipulate the stored information.

Rules for Naming Variables

  1. Variable names must begin with a letter or an underscore(_). And the names may contain the letters ‘a-z’ or ’A-Z’ or digits 0-9 as well as the character ‘_’.
    AppDividend, apps, _dividend  // valid variable
    123apps, '2appdividend      // invalid variable
    
  2. A variable name should not start with a digit.
    11appdividend  // illegal variable
  3. The name of the variable is case sensitive.
    apps and Apps are two different variables
  4. Keywords are not allowed to use as the variable name.
  5. There is no limit on the length of the name of the variable, but it is advisable to use an optimum length of 4 – 15 letters only.

Declaring a single variable

Using var keyword: In Go language, variables are created using the var keyword of a particular type, connected with the name, and provide its initial value.

Syntax:

var variable_name type = expression

Important Points:

  1. In the above syntax, either type or = expression can remove, but not both, can remove in the declaration of a variable.
  2. If the type is removed, then the type of the variable is determined by the value-initialize in the expression.

The var name type is the syntax to declare a single variable.

package main

import "fmt"

func main() {
	var series string // variable declare
	fmt.Println(series)
}

The statement var series string declares the variable named series of type string. We have not assigned any value for the series variable.

If a variable is not assigned any value, go automatically initializes it with the empty value or 0(if its integer)of the variable’s type. In this case, the series is assigned the empty value. If the variable is an integer, then 0 will be assigned.

If you execute the above program, you can see that the variable’s value is empty.

Declare a variable with an initial value

See the following code.

// hello.go

package main

import "fmt"

func main() {
	var series string = "The Witcher"
	fmt.Println(series)
}

Output

go run hello.go
The Witcher

Different data types

Let’s see an example where we declare different data type variables.

// hello.go

package main

import "fmt"

func main() {

	var game = 20
	var kgb = "Stranger In Moscow"
	var lockey = true

	fmt.Printf("The value of game is : %d\n",
		game)

	fmt.Printf("The type of game is : %T\n",
		game)

	fmt.Printf("The value of kgb is : %s\n",
		kgb)

	fmt.Printf("The type of kgb is : %T\n",
		kgb)

	fmt.Printf("The value of lockey is : %t\n",
		lockey)

	fmt.Printf("The type of lockey is : %T\n",
		lockey)

}

Output

go run hello.go
The value of game is : 20
The type of game is : int
The value of kgb is : Stranger In Moscow
The type of kgb is : string
The value of lockey is : true
The type of lockey is : bool

A variable can be assigned to any value of its data type. In the above program, the game is assigned an integer value, KGB has a string value, and lockey has a boolean value.

Type inference in Golang

If the variable has an initial value, Go will automatically be able to infer the type of that variable using that initial value. Hence if the variable has an initial value, the type in the variable declaration can be omitted.

If a variable is declared using the syntax var name = initialvalue, Golang will automatically infer the type of that variable from an initial value. Go will understand the type of initialized variables.

See the following code.

// hello.go

package main

import "fmt"

func main() {

	var game = 20
	fmt.Printf("The value of game is : %d\n",
		game)

	fmt.Printf("The type of game is : %T\n",
		game)
}

In the above code, we have defined a variable = 20, which means the game variable has type integer because 20 is an integer value, so we do not need to define its data type explicitly.

Multiple variable declaration

Multiple variables can be declared in a single statement in Go.

The var name1, name2 type = initialvalue1, initialvalue2 is the syntax for Golang multiple variable declaration.

See the following code.

// hello.go

package main

import "fmt"

func main() {

	var game, set = 1, 2
	fmt.Printf("The value of game is : %d\n",
		game)

	fmt.Printf("The value of set is : %d\n",
		set)
}

Output

go run hello.go
The value of game is : 1
The value of set is : 2

If an initial value is not defined for the game and set variables, then they will have 0 assigned as their initial value.

// hello.go

package main

import "fmt"

func main() {

	var game, set int
	fmt.Printf("The value of game is : %d\n",
		game)

	fmt.Printf("The value of set is : %d\n",
		set)
}

Output

go run hello.go
The value of game is : 0
The value of set is : 0

Golang short variable declaration

Golang also provides another concise way of declaring variables. This is known as the shorthand declaration, and it uses:= operator.

The local variables which are declared and initialize in the functions are declared by using a short variable declaration.

Shorthand declaration requires initial values for all variables on the left-hand side of the assignment.

See the short variable declaration syntax.

variable_name:= expression

See the following code.

// hello.go

package main

import "fmt"

func main() {

	askingPrice := 100
	payingPrice := 50
	fmt.Println("Asking Price is", askingPrice, "Paying price is", payingPrice)
}

Output

go run hello.go
Asking Price is 100 Paying price is 50

Most of the local variables are declared and initialized by using short variable declarations due to their brevity and flexibility.

The var declaration of variables is used for those local variables which need an explicit type that differs from the initializer expression, or for those variables whose values are assigned later and the initialized value is unimportant.

Using a short variable declaration, you are allowed to declare multiple variables in the single declaration.

Shorthand syntax can only be used when at least one of the variables on the left side of:= is newly declared. See the following code.

// hello.go

package main

import "fmt"

func main() {
	el, mike := 11, 21
	fmt.Println("el is", el, "mike is", mike)
	mike, kb := 10, 19
	fmt.Println("mike is", mike, "kb is", kb)
	mike, kb = 30, 46
	fmt.Println("changed mike is", mike, "kb is", kb)
}

Output

go run hello.go
el is 11 mike is 21
mike is 10 kb is 19
changed mike is 30 kb is 46

Multiple short variables declaration

See the following code.

// hello.go

package main

import "fmt"

func main() {

	name, series, age := "Millie", "Stanger Things", 16
	fmt.Println("Name is", name)
	fmt.Println("Series is", series)
	fmt.Println("Age is", age)
}

Output

go run hello.go
Name is Millie
Series is Stanger Things
Age is 16

Using a short variable declaration, you are allowed to declare multiple variables of different types in the single declaration. The expression determines the type of these variables.

Conclusion

In Golang, we can declare a variable without an initial value, with an initial value, with shorthand syntax, or direct assign the value to the value without declaring a variable.

We can also declare multiple variables in the same line with initial values.

Finally, Golang Variables Example is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.