英文:
Why would we use blank identifiers in Go?
问题
我发现对于空白标识符的使用有点难以理解。我已经查看了《Effective Go》,并理解了他们描述的大多数用例,但是在查看教程时,我在一个路由处理函数中遇到了以下代码:
var person Person
_ = json.NewDecoder(req.Body).Decode(&person)
在第一行中,我们创建了一个类型为Person的新空变量(之前定义的结构体),然后我假设:
&person
是将person变量通过引用传递,- 以便由
Decode
函数填充数据。
然后,该函数继续执行一些其他任务,然后对数据进行编码并返回JSON响应。
为什么我们需要将解码赋值给一个空白标识符?我们不能只运行json.NewDecoder(req.Body).Decode(&person)
吗?如果不能,为什么?
英文:
I'm finding the use of the blank identifier a little hard to understand. I've looked at effective go and understand most of the use cases they describe but then looking at a tutorial I came across this in a route handler function:
var person Person
_ = json.NewDecoder(req.Body).Decode(&person)
in the first line we create a new empty variable of type Person (a struct previously defined) and then I assume that
&person
is passing the person var in by reference,- to be filled with data by the
Decode
function
this function then goes on to perform a few more tasks before encoding and returning a json response.
Why do we need have the decode assigned to a blank identifier? Couldn't we just run json.NewDecoder(req.Body).Decode(&person)
? if we can't, why not?
答案1
得分: 1
我假设你正在学习Go语言,并且询问是因为你无法理解为什么这个例子使用了这种做法。
正如@JimB在评论中提到的,这个例子的作者并不需要这样做,他们只是忽略了错误返回。
英文:
I'm assuming you're learning golang and asking because you can't identify why this example used this practice.
As @JimB mentioned in comments, the example writer didn't need to do this they're simply ignoring the Error return.
答案2
得分: 1
空白标识符_
也可以用于严格地在结构体中提供键。参考这个链接。
不强制指定键:
type SomeStruct struct {
FirstField string
SecondField bool
}
myStruct := SomeStruct{"", false}
强制指定键值(消除对值排序的依赖):
type SomeStruct struct {
FirstField string
SecondField bool
_ struct{}
}
// 编译错误
myStruct := SomeStruct{"", false}
上述代码将报错SomeStruct
字面量中的值过少。
英文:
The blank identifier _
can be used to strictly provide the keys in a struct too. See this for reference
Without enforcing
type SomeStruct struct {
FirstField string
SecondField bool
}
myStruct := SomeStruct{"", false}
Enforcing to mention the key for the value (Removes the dependency of ordering the values)
type SomeSturct struct {
FirstField string
SecondField bool
_ struct{}
}
// COMPILATION ERROR
myStruct := SomeSturct{"", false}
The above will give the error too few values in SomeSturct literal
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论