CodeBlanks Logo Icon CodeBlanks

const and iota

Learn const for constants and iota for auto-increment.

const and iota

Constant values use the const keyword. After const Pi = 3.14, Pi cannot be changed; it is a compile error.

For enum-like structures, Go uses iota. In a const block, iota increments on each line; the first line starts at 0.

Constants are computed at compile time and do not change at runtime. This makes them preferred for performance and safety.

Using iota

iota produces a line-by-line incrementing number in a const block. For example:

const (
  A = iota
  B
  C
)

Here A=0, B=1, C=2. This is the standard way to define enum-like constants.

iota also works with bitwise ops: 1 << iota yields powers of two on each line.

Practice Days with iota

Define the constants Pazartesi (0), Sali and Carsamba with iota in a const block. Print fmt.Println(Pazartesi, Sali, Carsamba).

Starter code

main.go
package main

import "fmt"

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import "fmt"

const (
    Pazartesi = iota
    Sali
    Carsamba
)

func main() {
    fmt.Println(Pazartesi, Sali, Carsamba)
}

Expected output

0 1 2

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Can a const value be changed later?

  • Yes, with =
  • Only inside a function
  • No, a compile error Correct answer
  • Only through a pointer

Explanation: const values cannot be changed.

2 Constant declaration

Question
To declare the constant Pi:
____ Pi = 3.14
Answer
To declare the constant Pi:
const Pi = 3.14

Explanation: const declares a constant value.

3 Match the constant concepts

Term Meaning
const Constant
iota Auto-increment
Pi = 3.14 Fixed value
const block Enum-like

All lessons in Beginner