在围棋游显示了他们在同一行作为一个额外的声明为例:"如果"的声明,他们解释是这样的:the if statement can start with a short statement to execute before the condition.
func pow(x, n, lim float64) float64 {
if v := math.Pow(x, n); v < lim {
return v
}
return lim
}
Run Code Online (Sandbox Code Playgroud)
我不认为需要这种语法,并且发现它非常令人困惑.为什么不在v := math.Pow(x, n)
上一行写?
我问的原因是,对于我所发现的,语法在经过仔细考虑后进入Go语言,似乎没有任何想法.
我想我的实际问题是:他们试图通过使用这种语法来解决什么具体问题?使用以前没有的东西可以获得什么?
有许多用例,我不认为这个功能可以解决特定问题,但对于在Go中编码时遇到的一些问题,这是一个实用的解决方案.语法背后的基本意图是:
我记得的一些例子是我的头脑:
范围有限:
if v := computeStuff(); v == expectedResult {
return v
} else {
// v is valid here as well
}
// carry on without bothering about v
Run Code Online (Sandbox Code Playgroud)
错误检查:
if perr, ok := err.(*os.PathError); ok {
// handle path error specifically
}
Run Code Online (Sandbox Code Playgroud)
或更一般,类型检查:
if someStruct, ok := someInterface.(*SomeStruct); ok {
// someInterface is actually a *SomeStruct.
}
Run Code Online (Sandbox Code Playgroud)
地图中的密钥检查:
if _, ok := myMap[someKey]; ok {
// key exists
}
Run Code Online (Sandbox Code Playgroud)