Constant and Variables

 Variables In Golang

  • Variable in Golang or any other programming language is used to hold the data value. It could hold the value of type int, float, string, boolean, etc.
  • Variables in Golang are defined using the keyword var.
  • A variable can be defined either inside a main() function or outside a main() function in the same way.
  • You can define a list of variables in a single line by just writing the var keyword and then comma separating each variable name.


Example to Define A Variable

package main

import "fmt"

var d, name  //variables are defined outside function

func main() {
	var i int     //Variable is defined inside the function
	fmt.Println(i, d, name)


How to initialize variables in Golang?

  • If we assign a value to a variable then the variable will automatically take the type of initializer.
  • If the value is not assigned then we need to add an initializer in Golang.


package main

import "fmt"

var i, j int = 1, 2  //Here variable i and j are initialized as integers

func main() {
	var c, python, java = true, false, "no!"  //Here there is no initialization done
	fmt.Println(i, j, c, python, java)


Short Variable Declaration in Golang

  • Inside a function in golang. The short assignment could be using:= symbol.
  • Outside a function, we can not use short assignments as it is invalid.


package main

import "fmt"

func main() {
	var i, j int = 1, 2
	k := 3
	c, name, language := true, false, "no!"

	fmt.Println(i, j, k, c, name, language)


What are Zero Values in Golang?

  • Variables that are defined without any initial value in Golang are known as Zero Value variables.
  • For int type zero value is 0.
  • For Boolean it is false.
  • For strings it is "".


How to convert Type in Golang?

  • Converting type in golang is very easy. You just have to write the variable inside the small brackets with the type. For eg,
var num_int int = 42
var num_float float64 = float64(i)
var num_u uint = uint(f)


Constants In Golang

  • Constants in golang are created in the same way as variables but it starts with the const keyword
  • Constants in go are created at the compile time. Even if they are defined in the functions they run at compile time.
  • In golang constants can only be numbers, characters, strings, and booleans.


Example to Define a Constant

package main

import "fmt"

const Pi = 3.14

func main() {
	const Name = "World"
	fmt.Println("Hello", Name)

	const Rank = 100
	fmt.Println("Jee Rank = ", Rank)

    const Bool_eg = true
    fmt.Println("Output = ", Bool_eg)