在Go语言中并没有前置的++和--
比较符号- 相同维数且含有相同个数元素的数组才可以进行比较
- 当两个数组含有相同元素且顺序相同两个数组相同,否则不同
package test
import "testing"
func TestOperator(t *testing.T) {
a := [...]int{1, 2, 3, 4}
b := [...]int{1, 2, 3, 5}
d := [...]int{1, 2, 3, 4}
t.Log(a == b)//false
t.Log(a == d)//true
}
func TestOperator1(t *testing.T) {
a := [...] int {1, 2, 3, 4}
b := [...] int {1, 2, 3, 4, 5}
t.Log(a == b)//错误
}
报错:invalid operation: a == b (mismatched types [4]int and [5]int)
扩展的运算符按位置0, &^
例如 1 &^ 3 就是将 3 先取反,然后和 1 相与。
func TestOperator3(t *testing.T) {
a := 1
t.Log( a &^ 3)
}
循环和条件语句
go语言只支持for循环
package loop_test
import "testing"
func TestWhileLoop(t *testing.T) {
n := 1
//while (n < 5) {}
for n < 5 {
t.Log(n)
n++
}
}
条件语句
func TestCondition(t *testing.T) {
n := 1
if n > 1 {
t.Log("数字大于1")
} else if n < 1 {
t.Log("数字小于1")
} else {
t.Log("数字等于1")
}
}
但是条件语句支持赋值
func TestCodition1(t *testing.T) {
// error表示函数返回的错误, sum为一个函数
if a, error := sum(); error == nil{
t.Log("1 == 1")
} else {
t.Log("error")
}
}
与其他编程语言的差距
- 条件表达式不限制为常量或者是整数
- 单个case中,可以出现多个结果选项,使用逗号进行分隔
- 与C语言等规则相反,Go语言不需要break来明确退出一个case
- 可以不设定switch之后的表达式,在此情况下整个switch结构与多个if…else的逻辑作用等同
func TestCodition4(t *testing.T) {
for i := 0; i < 5; i++ {
switch i {
case 0, 2:
t.Log("Even")
case 1, 3:
t.Log("Odd")
default:
t.Log("it is not 0-3")
}
}
}
package main
import "fmt"
func main() {
var grade string = "B"
var marks int = 90
switch marks {
case 90: grade = "A"
case 80: grade = "B"
case 50,60,70 : grade = "C"
default: grade = "D"
}
switch {
case grade == "A" :
fmt.Printf("优秀!n" )
case grade == "B", grade == "C" :
fmt.Printf("良好n" )
case grade == "D" :
fmt.Printf("及格n" )
case grade == "F":
fmt.Printf("不及格n" )
default:
fmt.Printf("差n" );
}
fmt.Printf("你的等级是 %sn", grade );
}



