What does the underscore(_) do in for loop Golang?

huangapple go评论87阅读模式
英文:

What does the underscore(_) do in for loop Golang?

问题

我刚刚开始学习Golang语言!在for循环中,我看到有时会添加下划线,有时不添加下划线。

无论添加下划线与否,我得到的结果都是相同的。

我只知道我不关心索引。这就是全部吗?还是还有其他我需要知道的东西?

非常感谢你的帮助!

英文:

I am just getting started learning the Golang language!
In for loop, I saw sometimes adding an underscore or without underscore.

Whatever add _ or not, I got the same result.

package main

import (
	"fmt"
)

func main() {
	doSomething()
	sum := addValues(5, 8)
	fmt.Println("The sum is", sum)

	multiSum, multiCount := addAllValues(4, 7, 9)
	fmt.Println("multisum", multiSum)
	fmt.Println("multiCount", multiCount)
}

func doSomething() {
	fmt.Println("Doing Something")
}

func addValues(value1 int, value2 int) int {
	return value1 + value2
}

func addAllValues(values ...int) (int, int) {
	total := 0
	for _, v := range values {
		total += v
	}
	return total, len(values)
}
func addAllValues(values ...int) (int, int) {
	total := 0
	for v := range values {
		total += v
	}
	return total, len(values)
}

All I know is I don't care about the index. Is that all? or there is something more what I have to know??

I really appreciate your help!

答案1

得分: 7

对于对切片进行range循环:

  1. for v := range values {中,v是切片中元素的索引。
  2. for _, v := range values {中,v是实际的元素值。
  3. for i, v := range values {中,i是索引,v是元素。
  4. for i, _ := range values {中,i是切片中元素的索引。

你可以运行这个 playground的示例来查看它们之间的区别。


Range 表达式                          第一个值          第二个值

数组或切片  a  [n]E, *[n]E, or []E    索引    i  int    a[i]       E
字符串          s  string 类型            索引    i  int    详见下文  rune
映射             m  map[K]V                键      k  K      m[k]       V
通道         c  chan E, <-chan E       元素  e  E

更多细节请参阅规范

英文:

For range over slices:

  1. In for v := range values { the v is the index of the element in the slice.
  2. In for _, v := range values { the v is the actual element value.
  3. In for i, v := range values { the i is the index and the v is the element.
  4. In for i, _ := range values { the i is the index of the element in the slice.

You can run this playground example to see the differences.


Range expression                          1st value          2nd value

array or slice  a  [n]E, *[n]E, or []E    index    i  int    a[i]       E
string          s  string type            index    i  int    see below  rune
map             m  map[K]V                key      k  K      m[k]       V
channel         c  chan E, <-chan E       element  e  E

For more details see the spec.

答案2

得分: 1

如果你不想使用在循环中迭代的变量,你可以使用 _ 来让 Go 忽略它:

mySlice := [int]{1,3,4,59,5}
for _,x := range mySlice {
    fmt.Println(x)
}
英文:

If you don't want to use the variable that iterates in the loop, you can use _ to simply let Go ignore it:

mySlice := [int]{1,3,4,59,5}
for _,x := range mySlice {
    fmt.Println(x)
}

答案3

得分: 0

通过使用下划线,你告诉编译器这个意思:
好的,我知道这个函数返回了一些东西,但我不关心!例如:

package main

import "fmt"

func main() {
    mul1, add1 := test_function(2, 3)
    fmt.Println(mul1, add1)

    mul2, _ := test_function(4, 5)
    fmt.Println(mul2)

    _, add3 := test_function(7, 8)
    fmt.Println(add3)
}

func test_function(a int, b int) (mul int, add int) {
    return a * b, a + b
}
英文:

By placing underscore you are telling the compiler this:
Ok, I'm aware that this function is returning something but I don't care! For example:

package main

import "fmt"

func main() {
	mul1, add1 := test_function(2, 3)
	fmt.Println(mul1, add1)

	mul2, _ := test_function(4, 5)
	fmt.Println(mul2)

	_, add3 := test_function(7, 8)
	fmt.Println(add3)
}

func test_function(a int, b int) (mul int, add int) {
	return a * b, a + b
}

答案4

得分: 0

只是为了补充上面令人惊叹的答案:
我认为其中一个主要的好处是保持程序的可读性:如果你用一个变量替换空白标识符,那么你必须使用它,否则你的程序将无法编译。
此外,通过忽略一个返回参数,这也减少了内存分配...

英文:

just to add to the amazing answer above:
I think one of the main benefits is to maintain readability in your program: if you replace the blank identifier with a variable then you have to use it or your program will not compile.
also this decrease memory allocation be neglecting one of the returned parameters...

huangapple
  • 本文由 发表于 2022年2月14日 15:15:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/71108290.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定