使用if语言的程序清单如下:
package main
import(
"fmt"
)
func main(){
b:=true
if b{
fmt.Println("b is true!")
}
}
运行结果如下:
b is true!
使用else语句的代码清单如下:
package main
import(
"fmt"
)
func main(){
b:=false
if b{
fmt.Println("b is true!")
} else{
fmt.Println("b is false!")
}
}
运行结果如下:
b is false!
使用else if语句的程序清单如下:
package main
import(
"fmt"
)
func main(){
i:=2
if i==3{
fmt.Println("i is 3")
} else if i==2{
fmt.Println("i is 2")
}
}
运行结果如下:
i is 2
使用switch语句的程序清单:
package main
import(
"fmt"
)
func main(){
i:=2
switch i{
case 2:
fmt.Println("Two")
case 3:
fmt.Println("Three")
case 4:
fmt.Println("Four")
}
}
运行结果如下:
Two
在switch语句中添加default case的程序清单:
package main
import(
"fmt"
)
func main(){
s:="c"
switch s{
case "a":
fmt.Println("The letter a!")
case "b":
fmt.Println("The letter b!")
default:
fmt.Println("I don't recognize that letter!")
}
}
运行结果如下:
I don't recognize that letter!
使用for语句进行循环的程序清单如下:
package main
import(
"fmt"
)
func main(){
i:=0
for i<10{
i++
fmt.Println("i is",i)
}
}
运行结果如下:
i is 1 i is 2 i is 3 i is 4 i is 5 i is 6 i is 7 i is 8 i is 9 i is 10
一个包含初始化语句和后续语句的for语句的程序清单如下:
package main
import(
"fmt"
)
func main(){
for i:=0;i<10;i++{
fmt.Println("i is",i)
}
}
运行结果如下:
i is 0 i is 1 i is 2 i is 3 i is 4 i is 5 i is 6 i is 7 i is 8 i is 9
包含range子句的for语句的程序清单如下:
package main
import(
"fmt"
)
func main(){
numbers:=[]int{1,2,3,4}
for i,n:= range numbers {
fmt.Println("The index of the loop is",i)
fmt.Println("The value from the array is",n)
}
}
//i和n是迭代变量。i用于存储索引值,n用于存储来自数组中的值。
//迭代变量从0开始。
运行结果如下:
The index of the loop is 0 The value from the array is 1 The index of the loop is 1 The value from the array is 2 The index of the loop is 2 The value from the array is 3 The index of the loop is 3 The value from the array is 4
使用defer语句的程序清单如下:
package main
import(
"fmt"
)
func main(){
defer fmt.Println("I am run after the function completes")
fmt.Println("Hello World!")
}
运行结果如下:
Hello World! I am run after the function completes
使用多条defer语句的程序清单:
package main
import(
"fmt"
)
func main(){
defer fmt.Println("I am the first defer statement")
defer fmt.Println("I am the second defer statement")
defer fmt.Println("I am the third defer statement")
fmt.Println("Hello World!")
}
运行结果如下:
Hello World! I am the third defer statement I am the second defer statement I am the first defer statement



