一、算数运算
package main import "fmt" //算数运算 func main() { var num1 int = 10 var num2 int = 3 fmt.Printf("%d-%d=%d\n", num1, num2, num1-num2) fmt.Printf("%d+%d=%d\n", num1, num2, num1+num2) fmt.Printf("%d*%d=%d\n", num1, num2, num1*num2) fmt.Printf("%d/%d=%d\n", num1, num2, num1/num2) fmt.Printf("%d%s%d=%d\n", num1, "%", num2, num1%num2) num1++ fmt.Println(num1) num1-- fmt.Println(num1) //fmt.Printf("%d\n",num1++) //fmt.Printf("%d\n",num1-num2) }
C:\Users\yjtzf\AppData\Local\Temp\GoLand\___1go_build_demo09_arthmetic_operation_go.exe 10-3=7 10+3=13 10*3=30 10/3=3 10%3=1 11 10
数组比较
package operator_test import "testing" //数组表,维数相同、顺序相同。值相同,比较结果为TRUE //长度不同的数据,无法通过编译 func TestCompareArray(t *testing.T) { a := [...]int{1, 2, 3, 4} b := [...]int{1, 2, 3, 4} //c := [...]int{1, 2, 3, 4, 5} d := [...]int{1, 2, 3, 6} t.Log(a == b) //t.Log(a == c) //invalid operation: a == c (mismatched types [4]int and [5]int) t.Log(a == d) }
=== RUN TestCompareArray operator_test.go:12: true operator_test.go:14: false --- PASS: TestCompareArray (0.00s) PASS
二、关系运算
package main import "fmt" //关系运算 func main() { var v1 int = 10 var v2 int = 11 fmt.Println(v1 == v2) fmt.Println(v1 != v2) fmt.Println(v1 > v2) fmt.Println(v1 < v2) fmt.Println(v1 >= v2) fmt.Println(v1 <= v2) }
false true false true false true
三、布尔运算
//布尔运算 func main() { var flag1 bool = true var flag2 bool = false //与 都为真,结果为真 fmt.Println(flag1 && flag2) //或 有一个为真,结果为真 fmt.Println(flag1 || flag2) //非 取反 fmt.Println(!flag1) fmt.Println(!flag2) }
false true false true
四、位运算
&^清零运算符,a&^b,右侧为1,左侧清零,右侧为0,左侧保持。
1&^0 1
0&^1 0
1&^1 0
0&^0 0
package main import "fmt" //位运算 func main() { var a int = 60 var b int = 13 fmt.Printf("%d的二进制:%b,%d的二进制:%b \n", a, a, b, b) //按位与 都为1,结果为1 fmt.Printf("%b%s%b=%b %d\n", a, "&", b, a&b, a&b) //按或 都为0结果为0 fmt.Printf("%b%s%b=%b %d\n", a, "|", b, a|b, a|b) //按位非 不同为1,相同为0 fmt.Printf("%b%s%b=%b %d\n", a, "^", b, a^b, a^b) //位清空 对于b,若果是0取a位对应的值,如果是1取0 fmt.Printf("%b%s%b=%b %d\n", a, "&^", b, a&^b, a&^b) //左移运算 x2 fmt.Printf("%b%s=%b %d\n", a, "<<", a<<2, a<<2) //右移运算 /2 fmt.Printf("%b%s=%b %d\n", a, ">>", a>>2, a>>2) }
60的二进制:111100,13的二进制:1101 111100&1101=1100 12 111100|1101=111101 61 111100^1101=110001 49 111100&^1101=110000 48 111100<<=11110000 240 111100>>=1111 15