douti8321
douti8321
2014-07-26 17:29
采纳率: 0%
浏览 160
已采纳

如何在Go中的if语句中更新变量的值?

I'm trying to learn Go and I've created a function where I declare a variable game_ratio and set it to 0.0. I then have an if statement where I try and update the value of game_ratio. When I try and compile, I get the following error message: 'game_ratio declared and not used'

Here's my function:

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
", score1, scaled_score_1)
    fmt.Printf("Scaled score for %v is %v
", 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
}

Here's the code to call it:

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 is another function I have written. If I remove the if statement, the code works.

To run my app, I type 'rankings 28 24'

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douhoulei4706
    douhoulei4706 2014-07-26 17:37
    已采纳

    The short variable declaration is redeclaring game_ratio.

    game_ratio := (scaled_score_1+1.0)/(scaled_score_1+scaled_score_2+2.0) + 1.0*0.5
    

    Use an assignment. Write:

    game_ratio = (scaled_score_1+1.0)/(scaled_score_1+scaled_score_2+2.0) + 1.0*0.5
    

    The Go Programming Language Specification

    Short variable declarations

    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.

    点赞 评论

相关推荐