Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

golang - Why ++ and -- not work in expressions?

Tags:

go

What we take for granted in other languages and almost expect it to work in go, won't work - its almost so natural to do this, so why isn't the compiler happy? Just feeling like bailing out of go sometimes.

The only way to increment the value is to put it in its own separate line?

http://play.golang.org/p/_UnpZVSN9n

package main

import "fmt"
import "strconv"

func main() {
    a := 1
    //Evaluate expression and pass into function - won't work
    fmt.Println(strconv.Itoa(a++))
    //Braces around a++ also won't work
    fmt.Println(strconv.Itoa((a++)))
}
like image 935
sat Avatar asked Oct 23 '25 14:10

sat


2 Answers

++ and -- are statements in golang, not expressions

like image 175
aromero Avatar answered Oct 26 '25 11:10

aromero


Specifically, ++ and -- are statements because it can be very difficult to understand the order of evaluation when they're in an expression.

Consider the following:

// This is not valid Go!
x := 1
x = x++ + x
y := 1
y = ++y + y

What would you expect x to be? What would you expect y to be? By contrast, the order of evaluation is very clear when this is a statement.

like image 39
user2871145 Avatar answered Oct 26 '25 11:10

user2871145



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!