-1

I have code that loops through each rune of a string like so:

for i, character := range "abcdefghjklmnopqrstuv" {
    fmt.Printf("character and i: ", character, i)
}

However, I have no need do anything with i. I only need that for the loop to work. If I leave i out of fmt.Printf, the compiler complains that I have defined something I did not use. If I leave i in, it clutters my console output.

How can I can tell the compiler to ignore the unused variable?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Mamun
  • 2,322
  • 4
  • 27
  • 41
  • 2
    Does this answer your question? [How to avoid annoying error “declared and not used”](https://stackoverflow.com/questions/21743841/how-to-avoid-annoying-error-declared-and-not-used) or [Go: Unused variable](https://stackoverflow.com/questions/33802798/go-unused-variable) – John Kugelman Apr 12 '21 at 16:43
  • Thank you. It does! – Mamun Apr 12 '21 at 23:44
  • Late in the game, but I've had enought of unused variable error, so I've created a GoLand plugin to solve it similar to GoImports tool: https://plugins.jetbrains.com/plugin/20933-painlessgo Preview: https://youtu.be/sVVlDtQUXtU – David Horáček Feb 10 '23 at 11:36

2 Answers2

4

Use the blank identifier _:

for _, character := range "abcdefghjklmnopqrstuv" {
    fmt.Printf("character: ", character)
}

This is covered in the Tour of Go.

Adrian
  • 42,911
  • 6
  • 107
  • 99
0

I understand the confusion.

Unlike most program languages Go does not allow unused variables. This is because of a design decision to enforce that on this level unlike as a optional choice for each developer as other languages do.

So you can use the blank identifier as another answer mentioned but this is because of the way Go works.

A_kat
  • 1,459
  • 10
  • 17