DEV Community

Discussion on: When Should I Use One Liner if...else Statements in Go?

Collapse
 
erebos-manannan profile image
Erebos Manannán • Edited

One of the most common uses for if ..; .. { } for me has been map access.

var data = map[string]string{}
func addToMap(key string, value string) {
  if _, ok := data[key]; ok {
    fmt.Printf("%s already in map", key)
    return
  }

  data[key] = value
}

Alternatively use !ok if you're interested in when it's NOT in the map. For anyone not familiar with _ it basically means "throw this away", i.e. in that if block I don't care about the stored value.

Collapse
 
joncalhoun profile image
Jon Calhoun

You are right - this is another very common use case and you can almost always use the initialization statement since your maps shouldn't typically have names like omgThisMapHasASuperLooongNameThatIsSoAnnoyingToType 😀