Shorthand return in Go (golang) -


the following code generates syntax error (unexpected ++ @ end of statement) in go 1.6 or 1.7:

package main  import "fmt"  var x int  func increment() int {         return x++   // not allowed }  func main() {   fmt.println( increment() ) } 

shouldn't permitted?

it's error, because ++ , -- in go statements, not expressions: spec: incdec statements (and statements have no results returned).

for reasoning, see go faq: why ++ , -- statements , not expressions? , why postfix, not prefix?

without pointer arithmetic, convenience value of pre- , postfix increment operators drops. removing them expression hierarchy altogether, expression syntax simplified , messy issues around order of evaluation of ++ , -- (consider f(i++) , p[i] = q[++i]) eliminated well. simplification significant. postfix vs. prefix, either work fine postfix version more traditional; insistence on prefix arose stl, library language name contains, ironically, postfix increment.

so code wrote can written as:

func increment() int {     x++     return x } 

and have call without passing anything:

fmt.println(increment()) 

note tempted still try write in 1 line using assignment, e.g.:

func increment() int {     return x += 1 // compile-time error! } 

but doesn't work in go, because assignment statement, , compile-time error:

syntax error: unexpected += @ end of statement


Comments