Go: Constants

Declare

Example:

package main

import "fmt"

const PI = 3.1412

func main() {
    const SC = "Simplecheatsheet"
    fmt.Println("Hello", SC)

    fmt.Println("Happy", PI, "Day")

    const Correct= true
    fmt.Println("Go rules?", Correct)
}

=> Output

Hello Simplecheatsheet
Happy 3.14 Day
Go rules? true

Integer Constant

some examples of Integer Constant:

85         /* decimal */
0213       /* octal */
0x4b       /* hexadecimal */
30         /* int */
30u        /* unsigned int */
30l        /* long */
30ul       /* unsigned long */
212         /* Legal */
215u        /* Legal */
0xFeeL      /* Legal */
078         /* Illegal: 8 is not an octal digit */
032UU       /* Illegal: cannot repeat a suffix */

Floating Type Constant

Following are the examples of Floating type constant:

3.14159       /* Legal */
314159E-5L    /* Legal */
510E          /* Illegal: incomplete exponent */
210f          /* Illegal: no decimal or exponent */
.e55          /* Illegal: missing integer or fraction */

String Literals

Syntax

type _string struct {
    elements *byte // underlying bytes
    len      int   // number of bytes
}

Some examples of string literals:

"hello, simplecheatsheet"
"hello, \
simplecheatsheet"
"hello, " "simple" "cheatsheet"

The const Keyword

const variable type = value;

Example:

package main

import "fmt"

func main() {
   const LENGTH int = 4
   const WIDTH int = 5   
   var area int

   area = LENGTH * WIDTH
   fmt.Printf("value of area : %d", area)   
}

=> Output

value of area : 20

Escape Sequence

A list of some of such escape sequence codes −

Escape sequenceMeaning
\\\ character
\’‘ character
\”” character
\?? character
\aAlert or bell
\bBackspace
\fForm feed
\nNewline
\rCarriage return
\tHorizontal tab
\vVertical tab
\oooOctal number of one to three digits
\xhh . . .Hexadecimal number of one or more digits

Leave a Reply

Your email address will not be published. Required fields are marked *