• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

Justin Joyce

Practical tips and tutorials about software development.

  • Standing Invitation
  • Featured Posts
  • Latest
  • About

Golang iota explained

Posted Apr 7, 2023 — Updated Jan 10, 2024

If you’ve worked in Go, you’ve likely seen iota. Here’s how the Go docs explain it:

Within a constant declaration, the predeclared identifier iota represents successive untyped integer constants.

– The Go Docs

That sort of makes sense, but let me put it into plain English.

iota is used when declaring a list of constants, and assigns each constant  in the list to an integer value.

– Me

Go’s iota defines lists of constants

iota is normally used for things like this:

const (
	Red = iota
	Green
	Blue
)

func main() {
	log.Println(Red, Green, Blue)
}
// 0, 1, 2

From the above example, you can see iota starts at 0 and increases by 1 for each subsequent constant.

However, you might not want a constant with a value of 0 due to the way Golang default values work; a 0 might mean you’re actually missing data. In that case, you have two options:

// Option 1
const (
	_ = iota // 0
    Red // 1
    Green // 2
    Blue // 3
)

// Option 2
const (
	Red = iota + 1 // 1
    Green // 2
    Blue // 3
)

I personally prefer option one, since an underscore is the Go convention for something we don't need, but either way works fine.

There are more complicated ways to use iota, but for those I’ll refer you back to the iota docs as I’ve never had to actually use any of them.

Filed Under: Golang

Primary Sidebar

Recent Posts

  • Every Built-In Vim Color Scheme (with screenshots)
  • Reverse a string in Python
  • Meeting Cost Calculator
  • Vim find and replace
  • What makes an effective development team

Categories

  • Arrays (5)
  • Command Line (9)
  • Dates (3)
  • Featured (7)
  • Git (7)
  • Golang (5)
  • Javascript (8)
  • Productivity (8)
  • Projects (4)
  • Python (15)
  • Regex (2)
  • Ruby (3)
  • Shell (2)
  • Thoughts (2)
  • Tips (11)
  • Tools (3)
  • Tutorials (1)
  • Vim (4)

Archives

  • July 2024 (1)
  • February 2024 (1)
  • January 2024 (1)
  • December 2023 (1)
  • November 2023 (1)
  • October 2023 (4)
  • September 2023 (1)
  • August 2023 (2)
  • July 2023 (5)
  • June 2023 (3)
  • May 2023 (6)
  • April 2023 (5)
  • March 2023 (5)
  • February 2023 (10)
  • January 2023 (6)
  • December 2022 (7)

Copyright © 2025 · Contact me at justin [at] {this domain}

  • Privacy Policy