Go Constant Definition

Introduction

The keyword const is used to declare constants in Go.

We must assign a value at the time of the constant declaration.

We can omit the type at the time the constant is declared.

The type of constant is the type of the value assigned to the constant.

package main /* ww w.  j ava  2s. c om*/

import "fmt"

const NAME string = "CSS"
const PRICE = 500

func main() {
  fmt.Println(NAME)
  fmt.Println(PRICE)
}

The name of the constant must starts with a letter or underscore, followed by letters, numbers or underscores.

By convention, constant names are usually written in uppercase letters.

Constants declaration can to be grouped to code block.

package main // w w w .j  av a2s.  c o  m

import "fmt"

const (
  PRODUCT  = "Website"
  QUANTITY = 1
  PRICE    = 42.42
  ONLINE  = true
)

func main() {
  fmt.Println(QUANTITY)
  fmt.Println(PRICE)
  fmt.Println(PRODUCT)
  fmt.Println(ONLINE)
}



PreviousNext

Related