Operations on numbers
From the spec of Go [1], we have the following list of arithmetic operators on numbers:
+ sum integers, floats, complex values, strings
- difference integers, floats, complex values
* product integers, floats, complex values
/ quotient integers, floats, complex values
% remainder integers
& bitwise AND integers
| bitwise OR integers
^ bitwise XOR integers
&^ bit clear (AND NOT) integers
<< left shift integer << unsigned integer
>> right shift integer >> unsigned integer
Because C has a huge influence on Go, we need to pay more attention to some non-sense arithmetic operations on characters and integer. However, testing those out is a little bit tricky. The texting code is shown below:
// go run math.go
package main
import "fmt"
func main(){
var i = 2;
var c = 'c'
// The next line won't compile
// fmt.Printf("'c' / 2 = %d\n", c /i)
fmt.Printf("'c' / 2 = %d\n", c / int32(i))
fmt.Printf("'c' / 2 = %d\n", 'c' / 2)
}
You should see the result as follows
'c' / 2 = 49
'c' / 2 = 49
Notice that if we use 'c' and 2 as a literal, the program will run. However, if we declare them explicitly, it won't work. According to the spec, characters in Go are alias of int32. By default, integer literals are assigned int type. Hence, if we cast the i variable to int32, the code will run as desired.
That being said, Go inherits C's character arithmetic with some minor changes.