# 运算符
Go 语言的运算符和其他编程语言基本相同,了解下即可
# 算术运算符
| |
| package main |
| |
| import ( |
| "fmt" |
| ) |
| |
| func main() { |
| a, b := 12, 20 |
| var c int |
| c = a + b |
| c = a - b |
| c = a * b |
| c = a / b |
| c = b / a |
| c = a % b |
| c = b % a |
| fmt.Println("c =", c) |
| |
| |
| |
| a++ |
| fmt.Println("a =", a) |
| b-- |
| fmt.Println("b =", b) |
| } |
# 关系运算符
| |
| package main |
| |
| import ( |
| "fmt" |
| ) |
| |
| func main() { |
| a, b := 12, 20 |
| fmt.Println("数字比较") |
| fmt.Println(a == b) |
| fmt.Println(a != b) |
| fmt.Println(a > b) |
| fmt.Println(a < b) |
| fmt.Println(a >= b) |
| fmt.Println(a <= b) |
| |
| c, d := "Jalen", "Jalen" |
| fmt.Println("字符串比较") |
| fmt.Println(c == d) |
| |
| e, f := "Jalen1", "Jalen2" |
| fmt.Println(e == f) |
| fmt.Println(e > f) |
| fmt.Println(e < f) |
| |
| g, h := "abc_a", "abc_b" |
| fmt.Println(g > h) |
| fmt.Println(g < h) |
| } |
# 逻辑运算符
| |
| package main |
| |
| import ( |
| "fmt" |
| ) |
| |
| func main() { |
| a, b := true, false |
| fmt.Println(a && b) |
| fmt.Println(a || b) |
| fmt.Println(!a) |
| fmt.Println(!b) |
| |
| |
| |
| |
| |
| |
| |
| } |
# 位运算符
| |
| package main |
| |
| import ( |
| "fmt" |
| ) |
| |
| func main() { |
| var a int = 50 |
| var b int = 60 |
| fmt.Println(a & b) |
| fmt.Println(a | b) |
| fmt.Println(a ^ b) |
| |
| fmt.Println(a << 2) |
| fmt.Println(b >> 2) |
| } |
# 赋值运算符
| |
| package main |
| |
| import ( |
| "fmt" |
| ) |
| |
| func main() { |
| var a int = 12 |
| var b int = 20 |
| var c int |
| |
| c = a + b |
| c += a |
| c -= a |
| c *= a |
| c /= a |
| c %= a |
| c <<= a |
| c >>= a |
| c &= a |
| c ^= a |
| c |= a |
| fmt.Println(c) |
| } |
# 其他运算符
| |
| package main |
| |
| import ( |
| "fmt" |
| ) |
| |
| func main() { |
| var a int = 4 |
| var b int32 |
| var c float32 |
| var ptr *int |
| |
| fmt.Printf("第 1 行 - a 变量类型为 = %T\n", a) |
| fmt.Printf("第 2 行 - b 变量类型为 = %T\n", b) |
| fmt.Printf("第 3 行 - c 变量类型为 = %T\n", c) |
| |
| |
| |
| ptr = &a |
| fmt.Printf("a 的值为 %d\n", a) |
| fmt.Printf("*ptr 为 %d\n", *ptr) |
| fmt.Printf("ptr 为 %d\n", ptr) |
| |
| |
| var num1 = 12 |
| var ptr1 int |
| ptr1 = num1 |
| fmt.Println(ptr1) |
| num1 = 20 |
| fmt.Println(ptr1) |
| |
| var num2 = 12 |
| var ptr2 *int |
| ptr2 = &num2 |
| fmt.Println(*ptr2) |
| num2 = 20 |
| fmt.Println(*ptr2) |
| } |
# 运算符优先级
优先级 | 运算符 |
---|
5 | * / % << >> & &^ |
4 | + - | ^ |
3 | == != < <= > >= |
2 | && |
1 | || |