Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

  1. Home
  2. Go Dictionary
  3. Constants / iota

Constants / iota

Constants define values that cannot be changed. Using iota, you can automatically generate sequential constants, similar to an enumerated type.

Syntax

// Single constant
const ConstName Type = value
const ConstName = value // type inference

// Constant block (iota is available)
const (
	ConstName1 = iota // 0
	ConstName2        // 1
	ConstName3        // 2
)

// Expression using iota
const (
	ConstName1 = iota * 2 // 0
	ConstName2             // 2
	ConstName3             // 4
)

Syntax Reference

SyntaxDescription
const name = valueDeclares a constant with type inference. Numbers, strings, and booleans are supported.
const name type = valueDeclares a constant with an explicit type.
const ( ... )A block that declares multiple constants together.
iotaA sequential counter available inside a const block. It resets to 0 at the start of each block and increments by 1 for each line.
_ = iotaUses a blank identifier to skip a specific value in the sequence.
1 << iotaA common idiom for defining bit-flag constants using a bit shift.

Sample Code

package main

import "fmt"

// Simple constants
const Pi = 3.14159
const AppName = "MyApp"

// Weekday constants using iota
type Weekday int

const (
	Sunday Weekday = iota // 0
	Monday                // 1
	Tuesday               // 2
	Wednesday             // 3
	Thursday              // 4
	Friday                // 5
	Saturday              // 6
)

// Bit-flag constants (using 1 << iota)
const (
	Read    = 1 << iota // 1 (001)
	Write               // 2 (010)
	Execute             // 4 (100)
)

func main() {
	fmt.Println(Pi, AppName)
	fmt.Println(Sunday, Monday, Saturday) // 0 1 6

	// Combining bit flags
	perm := Read | Write // 3 (011)
	fmt.Printf("perm: %d\n", perm)
	fmt.Printf("Has Read permission: %v\n", perm&Read != 0)
	fmt.Printf("Has Execute permission: %v\n", perm&Execute != 0)
}

Notes

Constants have their values determined at compile time, so you cannot assign a function's return value or a variable to a constant. Only numeric literals, strings, booleans, and other constants are valid.

iota is only valid inside a const block and resets to 0 at the start of each new block. Because it increments by 1 for each line, you can concisely define even complex sequential constants.

Using typed constants (constants defined with a custom type such as type Weekday int) lets the compiler catch unintended type mixing at compile time. Use them actively in combination with Go's basic data types.

If you find any errors or copyright issues, please .