Shorthand return in Go (golang)

前端 未结 2 841
时光说笑
时光说笑 2021-01-23 17:28

The following code generates a syntax error (unexpected ++ at end of statement) in Go 1.6 or 1.7:

package main

import \"fmt\"

var x int

func          


        
2条回答
  •  盖世英雄少女心
    2021-01-23 18:27

    The accepted solution is right that the OP's code does not work because in go increment/decrement(x++/x--) statements are expressions that don't return a value.

    However the solution presented has a slightly different effect than the original request.

    x++ would return the value of x then increment in C like syntax.

    however the opposite would happen if you do it this way:

    x++
    return x
    

    You can negate that issue by reducing your initial value by one or by using a defer statement as written here:

    func incr() int {
        defer func() { counter++ }()
        return counter
    }
    

    https://play.golang.org/p/rOuAv7KFJQw

提交回复
热议问题