本文介绍了什么是“_”,“在Golang声明中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Golang的新手,想要学习它,来自PHP和Java。



我似乎无法理解这种变量声明:

  _,prs:= m [example] 

_是什么,干什么和为什么要声明一个这样的变量而不是

  prs:= m [example] 




感谢您的帮助!

解决方案

它避免了必须声明返回值的所有变量。 >
它被称为。



如:

  _,y,_:= coord (p)// coord()返回三个值;只对y坐标感兴趣

()



丢弃返回值,当您只想检查其中一个返回值时,这很有用,如中显示的地图?:

  _,present:= timeZone [tz] 



由于增加了中:



 <$ c $(范围)(值),使用空白标识符,下划线来放弃第一个: c> sum:= 0 
for _,value:=范围数组{
sum + = value
}


I am new to Golang and trying to learn it, coming from PHP and Java.

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

_, prs := m["example"]

What exactly is "_," doing and why have they declared a variable like this instead of

prs := m["example"]

I found it in this example:https://gobyexample.com/maps

Thanks for helping me out!

解决方案

It avoids having to declare all the variables for the returns values.
It is called the blank identifier.

As in:

_, y, _ := coord(p)  // coord() returns three values; only interested in y coordinate

(the other '_' use case is for import)

Since it discards the return value, it is helpful when you want to check only one of the returned values, as in "How to test key existence in a map?" shown in "Effective Go, map":

_, present := timeZone[tz]

As Jsor adds in the comments:

That allows you to combine it with test:

if _, err := os.Stat(path); os.IsNotExist(err) {
    fmt.Printf("%s does not exist\n", path)
}

You would find it also in loop:

sum := 0
for _, value := range array {
    sum += value
}

这篇关于什么是“_”,“在Golang声明中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-27 17:49
查看更多