我正在尝试学习围棋,我创建了一个函数,我在其中声明了一个变量 game_ratio 并将其设置为 0.0。然后我有一个 if 语句,我在其中尝试更新 game_ratio 的值。当我尝试编译时,收到以下错误消息: 'game_ratio 已声明但未使用'
这是我的功能:
func gameRatio(score1 int, score2 int, max_score float64) float64 {
var game_ratio float64 = 0.0
var scaled_score_1 = scaleScore(score1, max_score)
var scaled_score_2 = scaleScore(score2, max_score)
fmt.Printf("Scaled score for %v is %v\n", score1, scaled_score_1)
fmt.Printf("Scaled score for %v is %v\n", score2, scaled_score_2)
if score1 > score2 {
game_ratio := (scaled_score_1+1.0)/(scaled_score_1+scaled_score_2+2.0) + 1.0*0.5
}
return game_ratio
}
下面是调用它的代码:
func main() {
flag.Parse()
s1 := flag.Arg(0)
s2 := flag.Arg(1)
i1, err := strconv.Atoi(s1)
i2, err := strconv.Atoi(s2)
if err != nil {
fmt.Println(err)
os.Exit(2)
}
fmt.Println("Game ratio is", gameRatio(i1, i2, 6))
}
ScaleScore 是我编写的另一个函数。如果我删除 if 语句,代码就可以工作。
要运行我的应用,我输入“rankings 28 24”
最佳答案
简短的变量声明是重新声明game_ratio
。
game_ratio := (scaled_score_1+1.0)/(scaled_score_1+scaled_score_2+2.0) + 1.0*0.5
使用赋值。写:
game_ratio = (scaled_score_1+1.0)/(scaled_score_1+scaled_score_2+2.0) + 1.0*0.5
The Go Programming Language Specification
A short variable declaration uses the syntax:
ShortVarDecl = IdentifierList ":=" ExpressionList .
It is shorthand for a regular variable declaration with initializer expressions but no types:
"var" IdentifierList = ExpressionList .
Unlike regular variable declarations, a short variable declaration may redeclare variables provided they were originally declared earlier in the same block with the same type, and at least one of the non-blank variables is new. As a consequence, redeclaration can only appear in a multi-variable short declaration. Redeclaration does not introduce a new variable; it just assigns a new value to the original.
关于go - 如何在 Go 中的 if 语句中更新变量的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24973665/