Operators in Go
By Flavio Copes
An overview of operators in Go, from assignment and comparison to arithmetic, increment and decrement, and the boolean &&, || and ! operators.
Go gives us a small set of operators: assignment, comparison, arithmetic, increment and decrement, and the boolean operators. We used some of them so far in our code examples, like =, := and <.
Let’s talk a bit more about them.
Assignment operators
We have assignment operators = and := we use to declare and initialize variables:
var a = 1
b := 1
The difference: := declares and assigns in one step, and it only works inside functions. At the package level, outside any function, you must use var.
We also have compound assignment operators that update a variable in place:
count := 10
count += 5 //count == 15
count -= 3 //count == 12
count *= 2 //count == 24
Comparison operators
We have comparison operators == and != that take 2 arguments and return a boolean
var num = 1
num == 1 //true
num != 1 //false
and <, <=, >, >=:
var num = 1
num > 1 //false
num >= 1 //true
num < 1 //false
num <= 1 //true
Arithmetic operators
We have binary (require two arguments) arithmetic operators, like +, -, *, /, %.
1 + 1 //2
1 - 1 //0
1 * 2 //2
2 / 2 //1
2 % 2 //0
Be careful with division. When both operands are integers, the result is an integer too, and Go drops the decimal part:
7 / 2 //3, not 3.5
If you want the decimal result, at least one operand must be a float:
7.0 / 2 //3.5
Also note that Go never mixes types in arithmetic. Adding an int variable to a float64 variable is a compile error. You fix it with an explicit conversion, like float64(num).
+ can also join strings:
"a" + "b" //"ab"
Increment and decrement
We have unary operators ++ and -- to increment or decrement a number:
var num = 1
num++ // num == 2
num-- // num == 1
Note that unlike C or JavaScript we can’t prepend them to a number like
++num. Also, the operation does not return any value.
This means you can’t write something like a := num++. In Go, num++ is a statement, not an expression. It’s one less category of subtle bugs.
Boolean operators
We have boolean operators that help us with making decisions based on true and false values: &&, || and !
true && true //true
true && false //false
true || false //true
false || false //false
!true //false
!false //true
&& and || short-circuit. If the left side of && is false, the right side never runs. Same with || when the left side is true. This is useful when the right side is a function call you only want to happen conditionally.
Those are the main ones.