GoLang Constants and Literals | GoLang Tutorial

5 years ago Lalit Bhagtani 0

In this tutorial, we will learn about constants and literals in Go programming language.

GoLang Constants

A Constant is a variable, whose value cannot be changed once assigned. In other words, Constant variable is immutable in nature. In GoLang, Constant variable can be of type string, boolean and numeric ( integer, floating-point, complex ).

A Constant variable is declared using const keyword. 

Syntax

const <variable-name> <data-type> = <value> 
const name = "CodeDestine"

Example

package main

import ("fmt")

// Package Level Constant
const name string = "CodeDestine"

// Package Level Constant (Declaring multiple)
const (
   age int32 = 30
   designation string = "Employee"
)

func main() {
   // Function Level Constant
   const city string = "New York"

   // Function Level Constant (Declaring multiple)
   const (
      zip int32 = 560008
      currency string = "USD"
   )
   
   fmt.Println(zip)
}

GoLang Literals

A literal is a fixed value assigned to variables or constants.

Integer Literals

An integer literal can be a decimal, octal, or hexadecimal value, a prefix indicates the base of the integer value like 0x or 0X for hexadecimal, 0 for octal, and nothing required for decimal value. An integer literal can also have a suffix that is a combination of U and L, for unsigned and long, respectively. The suffix can be uppercase or lowercase and can be in any order.

Example

54         /* decimal */
0113       /* octal */
0x4a       /* hexadecimal */
40         /* int */
40u        /* unsigned int */
40l        /* long */
40ul       /* unsigned long */

Floating Point Literals

A floating-point literal has an integer part, decimal point, fractional part, and an exponent part. You can represent floating point literals either in fractional form or in exponential form. In fractional form, you must include the decimal point, the exponent, or both and while in exponential form, you must include the integer part, the fractional part, or both. The signed exponent is introduced by e or E.

Example

3.14       /* Fractional Form */
3141E-5L   /* Exponential Form */

String Literals

A string literals are enclosed in double quotes ” “, and it contains a sequence of characters. A long string literals can be break into multiple lines using backslash.

Example

"Manager"        /* String */ 
"Hello, World"   /* String */ 

References

  1. Constants Docs

That’s all for Golang Constants and Literals, if you liked it, please share your thoughts in comments section and share it with others too.