Thursday, 2 May 2019

Go language: _ symbol


Unused variables in Go leads to compilation errors. You can get rid of the problem using _ symbol.

App.go
package main

import "fmt"

func main() {

 var vowels = []string{"a", "e", "i", "o", "u"}

 for i, v := range vowels {
  fmt.Printf("value %v\n", v)
 }

}


When you try to run above program, you will end up in below error.

# command-line-arguments
./App.go:9:6: i declared and not used

You can use _, to save you from unused variables.

for _, v := range vowels {
         fmt.Printf("value %v\n", v)
}


App.go
package main

import "fmt"

func main() {

 var vowels = []string{"a", "e", "i", "o", "u"}

 for _, v := range vowels {
  fmt.Printf("value %v\n", v)
 }

}

Output
value a
value e
value i
value o
value u




Previous                                                 Next                                                 Home

No comments:

Post a Comment