If statement 为什么在“引用”中使用语句;如果;陈述
显示了一个示例,其中它们在“if”语句的同一行中有一个额外语句,并且它们的解释如下:If statement 为什么在“引用”中使用语句;如果;陈述,if-statement,go,If Statement,Go,显示了一个示例,其中它们在“if”语句的同一行中有一个额外语句,并且它们的解释如下:if语句可以以一个短语句开始,在条件之前执行。 func pow(x, n, lim float64) float64 { if v := math.Pow(x, n); v < lim { return v } return lim } func-pow(x,n,lim-float64)float64{ 如果v:=数学功率(x,n);v
if语句可以以一个短语句开始,在条件之前执行。
func pow(x, n, lim float64) float64 {
if v := math.Pow(x, n); v < lim {
return v
}
return lim
}
func-pow(x,n,lim-float64)float64{
如果v:=数学功率(x,n);v
我不认为有必要使用这种语法,并且觉得它非常混乱。为什么不在前一行写v:=math.Pow(x,n)
我问这个问题的原因是,我发现,经过仔细考虑,语法进入了围棋语言,似乎没有什么是出于一时兴起
我想我的实际问题是:他们使用这种语法试图解决什么具体问题?通过使用它,您获得了什么以前没有的好处?因为您的变量包含在范围中 请注意,这些
v
声明在不同的范围内
了解作用域的更直接示例:
有很多用例,我不认为这个特性可以解决一个特定的问题,但是它是一个实用的解决方案,可以解决您在编写Go代码时遇到的一些问题。语法背后的基本意图是:
- 适当的作用域:只为变量提供它需要的作用域
- 正确的语义:明确变量只属于代码的特定条件部分
if v := computeStuff(); v == expectedResult {
return v
} else {
// v is valid here as well
}
// carry on without bothering about v
if perr, ok := err.(*os.PathError); ok {
// handle path error specifically
}
if someStruct, ok := someInterface.(*SomeStruct); ok {
// someInterface is actually a *SomeStruct.
}
if _, ok := myMap[someKey]; ok {
// key exists
}
错误检查:
if v := computeStuff(); v == expectedResult {
return v
} else {
// v is valid here as well
}
// carry on without bothering about v
if perr, ok := err.(*os.PathError); ok {
// handle path error specifically
}
if someStruct, ok := someInterface.(*SomeStruct); ok {
// someInterface is actually a *SomeStruct.
}
if _, ok := myMap[someKey]; ok {
// key exists
}
或更一般的,类型检查:
if v := computeStuff(); v == expectedResult {
return v
} else {
// v is valid here as well
}
// carry on without bothering about v
if perr, ok := err.(*os.PathError); ok {
// handle path error specifically
}
if someStruct, ok := someInterface.(*SomeStruct); ok {
// someInterface is actually a *SomeStruct.
}
if _, ok := myMap[someKey]; ok {
// key exists
}
键检入地图:
if v := computeStuff(); v == expectedResult {
return v
} else {
// v is valid here as well
}
// carry on without bothering about v
if perr, ok := err.(*os.PathError); ok {
// handle path error specifically
}
if someStruct, ok := someInterface.(*SomeStruct); ok {
// someInterface is actually a *SomeStruct.
}
if _, ok := myMap[someKey]; ok {
// key exists
}
范围在关闭大括号之后和返回lim之前,
v
是否仍在范围内?我想不会,这就是为什么它是这样写的。带有ok
标志的类型断言很酷!“我没有看到太多这样的内容。@SimonWhitehead这很遗憾,因为你应该经常检查类型断言:)尽管我已经很久没有玩Go了,所以我对其他人写的Go的接触是相当有限的:)这也许可以向这里的一些常客解释为什么我会留下如此激动人心的评论!:D也可能是因为他们意识到,if(s=getChar())
的C构造非常有用,而BL也是一种邪恶的东西,不能很好地处理多个返回值。