0

I saw a piece of code used to print values passed in arguments:

package main

import "fmt"
import "os"

func main() {
  for _, val := range os.Args[1:] {
     fmt.Printf("%d %s \n", _ , val)
  }
}

Original program had a note that _ holds index but was not printing it. When I tried to print index, I am getting below error: ./main.go:8:16: cannot use _ as value

What is the issue here?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189

1 Answers1

8

_(underscore) in Golang is known as the Blank Identifier and it's value can't be used(it kind of doesn't hold any value).

Go doesn't allow you to have a unused variable therefore, original program used _ to drop the value and compile the program successfully. Use i instead of _ and run the program.

package main

import "fmt"
import "os"

func main() {
  for i, val := range os.Args[1:] {
     fmt.Printf("%d %s \n", i , val)
  }
}
codingenious
  • 8,385
  • 12
  • 60
  • 90
  • Please note this is different from python where using `_` is just a naming convention – Mark Oct 25 '22 at 20:28