Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Last Updated: Mar 27, 2024

Variables and Constants in Go

Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

Variables are a key component of all programs as they store data. Constants, the name suggests, do not change their value throughout the program. Like every other programming language, Go has data types to define the variables they use in the program. Go does not allow variables of different data types to participate in the same operation. Let us explore how to use variables and constants in Go.

Variables in Go

In general, a variable is a name of a memory location. The value that the location stores can be changed through the course of the program. In Go, certain conventions are to be followed to name variables. The following rules are common to variables and constants.

  • A variable name can start only with a letter or an underscore.
     
  • It can be followed by any number of alphabets, numbers or underscores.
     
  • Go is case sensitive.
     
  • Keywords cannot be used as a variable name.
     

The var keyword is used to create the variables of a data type having a name and initial value. Initialising a variable during declaration is optional. If the programmer does not initialise it, the default value is assigned to the variable.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Declaring variables

Single variable declaration without an initial value

Syntax:

var <variable_name> <type>

 

Example:

package main

import "fmt"

func main(){
    var a int
    var f float
    fmt.Println(a)
    fmt.Println(f)
}


Here, the default value of int and float32 is 0. Hence, it is initialised to variables a and f, respectively.

Output:

0
0

Single variable declaration with an initial value

Syntax:

var <variable_name> <type> = <value>

Example:

package main

import "fmt"

func main(){
    var a int = 10
    var f float = -3.5
    fmt.Println(a)
    fmt.Println(f)
}

 

Output:

10
-3.5

Multiple variable declarations without initialisation

Syntax:

var <name1>, <name2>,....<nameN> <type>

Example:

package main

import "fmt"

func main(){
    var a, b int
    fmt.Println(a)
    fmt.Println(b)
}

 

Output:

0
0

Multiple variable declarations with initialisation

Syntax:

var <name1>, <name2>, .....,<nameN> <type> = <value1>, <value2>, .....,<valueN>

Example:

package main

import "fmt"

func main(){
    var a, b int = 10,20
    fmt.Println(a)
    fmt.Println(b)
}

 

Output:

10
20

Declare variables of different types

Multiple variables of different data types can be declared under a single var keyword. In the example shown below, since string b is not assigned any value, a default empty string is assigned to it.

Example:

package main

import "fmt"

func main(){
    var (
          a int = 10
          b string
          f float64 = -3.5)
    fmt.Println(a)
    fmt.Println(b)
    fmt.Println(f)
}

 

Output:

10 

-3.5

Variable Declaration with no type or Type Inference

Syntax:

var <variable_name> = <value>

Example:

package main

import "fmt"

func main(){
    var a = 10
    var f = -3.5
    fmt.Printf(“%v is of %T data type”,a,a)
    fmt.Printf(“\n%v is of %T data type”,f,f)
}

 

Output:

10 is of int data type
-3.5 is of float64 data type

 

In the above example, the Go compiler uses Type inference to identify the data type assigned to the variable.

Short variable declaration

The := operator in Go is used to declare variables without mentioning the var keyword and data type. Like the previous case, Type Inference is used to identify the data type of the value assigned to the variable.

Syntax:

<variable_name> := <value>

Example:

package main

import "fmt"

func main(){
    a := 10
    f := -3.5
    fmt.Printf(“%v is of %T data type”,a,a)
    fmt.Printf(“\n%v is of %T data type”,f,f)
}

 

Output:

10 is of int data type
-3.5 is of float64 data type

Constants in Go 

Constants in Go are declared and initialised only once in the whole program. This allows users to define a variable that will remain fixed throughout the compilation of the program.

The const keyword is used to declare a constant in Go.

Syntax:

const <const_name> = <value>

String constants

They have their values enclosed within double-quotes. Typed string constants have the data type string included within their syntax. In contrast, untyped constants have their data types identified by Type inference. The example below declares an untyped string constant whose value is then assigned to a variable. The word variable acquires its data type from the string constant. Constant s is a typed string constant.

package main

import "fmt"

func main() {  
    const n = "Hello"
    var word = n
    fmt.Printf("Type %T value %v", word, word)
    const s string = “World”
    fmt.Println("Type %T value %v", s, s)
}

 

Output:

Type string value Hello
Type string value World

Typed and Untyped Numeric constants

Typed Numeric constants are declared with their data type. Once declared they cannot hold values of any other data type. Untyped Numeric constants on the other hand are declared without mentioning their data type. The data type is identified by Type inference. Constant num1 is untyped while num2 is typed.

package main

import "fmt"

func main() {  
    const num1 = 2.3
    fmt.Printf("Type %T value %v", word, word)
    const num2 int = 4
    fmt.Println("Type %T value %v", s, s)
}

 

Output:

Type float64 value 2.3
Type int value 4

Numeric constants

Numeric constants can be assigned integers, floating-point numbers and complex numbers. 

Integer Constants

An Integer constant is assigned integer values including decimal, octal and hexadecimal. The following example shows an untyped integer constant being assigned a value of 5. This value is then assigned to another variable a.

package main

import "fmt"

func main() {  
    const num = 5
    var a = num
    fmt.Printf("Type %T value %v", a, a)
}

 

Output:

Type int value 5

 

Floating-Point Constants

Floating-point constants involve values with an integer part, a decimal point, a fractional part and an exponent. 

package main

import "fmt"

func main() {  
    const num = 5.3
    fmt.Printf("Type %T value %v", a, a)
}

 

Output:

Type float64 value 5.3

 

Complex Constants

Complex constants are represented as an ordered pair of an integer constant and an imaginary constant. The example shows number 5  as a complex number because of the data type assigned to it. 

package main

import "fmt"

func main() {  
    const ch complex64 = 5
    fmt.Printf("Type %T value %v", ch, ch)
}

 

Output:

Type complex64 value (5+0i)

Boolean constants

They are very much similar to string constants but can define only true or false.

package main

import "fmt"

func main() {  
    const a = true
    var b = a
    fmt.Printf("Type %T value %v", b, b)
}

 

Output:

Type bool value true

FAQs

  1. What is the static type declaration of a variable in Go?

    Static type declaration tells the Go compiler that the variable exists with a given type and name, so it can proceed to compile without requiring all the details of the variable. Variable declaration holds its meaning only at the compilation time.
     
  2. What is type inference?

    When a variable is declared without a data type and initialised with a value, its type is inferred from the value assigned on the right-hand side. It is extremely simple and works only in one language construct at a time.

Key Takeaways

This article extensively discusses variables and constants in Go. We hope that this blog has helped you enhance your knowledge about declaring and initialising variables and constants in Go. If you would like to learn more, check out our articles on the Coding Ninjas Library. Do upvote our blog to help other ninjas grow. Happy Coding!

Related Links:

What is Golang?

Dynamics of Golang

Topics covered
1.
Introduction
2.
Variables in Go
3.
Declaring variables
3.1.
Single variable declaration without an initial value
3.2.
Single variable declaration with an initial value
3.3.
Multiple variable declarations without initialisation
3.4.
Multiple variable declarations with initialisation
3.5.
Declare variables of different types
3.6.
Variable Declaration with no type or Type Inference
3.7.
Short variable declaration
4.
Constants in Go 
4.1.
String constants
4.2.
Typed and Untyped Numeric constants
4.3.
Numeric constants
4.3.1.
Integer Constants
4.3.2.
Floating-Point Constants
4.3.3.
Complex Constants
4.4.
Boolean constants
5.
FAQs
6.
Key Takeaways