What is “_,” (underscore comma) in a Go declaration?

后端 未结 8 969
耶瑟儿~
耶瑟儿~ 2020-12-04 08:31

And I can\'t seem to understand this kind of variable declaration:

_, prs := m[\"example\"]

What exactly is \"_,\" doing and w

相关标签:
8条回答
  • 2020-12-04 08:53

    Basically, _, known as the blank identifier. In GO we can't have variables that are not being used.

    As an instance when you iterating through an array if you are using value := range you don't want a i value for iterating. But if you omit the i value it will return an error. But if you declare i and didn't use it, it will also return an error.

    Therefore, that is the place where we have to use _,.

    Also it is used when you don't want a function's return value in the future.

    0 讨论(0)
  • 2020-12-04 08:56

    The great use case for the unused variable is the situation when you only need a partial output. In the example below we only need to print the value (state population).

    package main
    import (
        "fmt"
    )
    func main() {
              statePopulations := map[string]int{
              "California": 39250017,
              "Texas":      27862596,
              "Florida":    20612439,
              }
              for _, v := range statePopulations {
              fmt.Println(v)
        }
    }
    
    0 讨论(0)
提交回复
热议问题