0

Question about For Loops in GO

Hello! So, just a small intro New to GO, well programming.. Within a for loop. I see the ' _ ' used. What does it do? I see references in python as a variable, but if I change ' _ ' to q var1 it fails. So what is this for _, Thank you in advanced! small snippet: package main import "fmt" func main() { nums := []int{2, 3, 4} sum := 0 for _, num := range nums { sum += num } fmt.Println(sum) } Output: 9

19th Jul 2022, 2:26 AM
Steve Oro
Steve Oro - avatar
1 Answer
+ 1
Steven Oro an array contains index and value and value access by index. Underscore (_) is used to skip index and get value without index. You can change _ to any variable but you have to use it otherwise error will come package main import "fmt" func main() { nums := []int{2, 3, 4} sum := 0 for var1, num := range nums { fmt.Println ("Index", var1) sum += num } fmt.Println(sum) } -----------access value using index--------- package main import "fmt" func main() { nums := []int{2, 3, 4} sum := 0 for var1 := range nums { sum += nums[var1] } fmt.Println(sum) } -------------
19th Jul 2022, 4:05 AM
AÍąJ
AÍąJ - avatar