본문 바로가기
Go

[Go] Constant

by llHoYall 2021. 10. 5.

A constant is an unchanged value.

Only primitive type can be defined as constant.

  • Boolean
  • Rune
  • Integer
  • Real Number
  • Complicated Number
  • String

The type that is not a primitive type like Structure, Array can't be defined as constant.

Constant Definition

const Name Type = Value

If the name starts with a capital letter, the constant is exposed to out of the file.

Constant Usage

package main

func main() {
  const a int = 7
  // a = 3	=> Error!
  // fmt.Printf("%p\n", &a)	=> Error!
}

Constant cannot be reassigned and cannot access its address.

In Go, a constant is treated as literal, i.e. a constant and constant expression is converted into literal in the compile-time.

Therefore, we cannot access the constant's address.

A constant is just a literal value, not a value on dynamic memory.

Typeless Constant

When defining a constant, a type may not be specified.

A type of typeless constant is determined when copied to a variable.

const PI = 3.14

var a int = PI * 100
var b float64 = PI * 100

fmt.Println(a, b)	// 314 314

Enumeration

We can use an enumerator in Go.

const (
  a int = iota
  b
  c
)
fmt.Println(a, b, c) // 0 1 2

We simply use the iota keyword with parentheses!

Let's take a look at the other application.

const (
  a int = iota + 3
  b
  c
)
fmt.Println(a, b, c) // 3 4 5

const (
  bit0 uint8 = 1 << iota
  bit1
  bit2
  bit3
)
fmt.Println(bit3, bit2, bit1, bit0) // 8 4 2 1

'Go' 카테고리의 다른 글

[Go] Array  (0) 2021.10.10
[Go] Control Flow  (0) 2021.10.10
[Go] The Error of Floating Point Number  (0) 2021.10.04
[Go] Operator  (0) 2021.10.04
[Go] File handling  (0) 2020.12.02

댓글