Skip to main content
Version: go

基本

if-else 结构

package main

import "fmt"

func main() {
var first int = 10
var cond int

if first <= 0 {
fmt.Printf("first is less than or equal to 0\n")
} else if first > 0 && first < 5 {
fmt.Printf("first is between 0 and 5\n")
} else {
fmt.Printf("first is 5 or greater\n")
}

// 给一个变量赋值
if cond = 5; cond > 10 {
fmt.Printf("cond is greater than 10\n")
} else {
fmt.Printf("cond is not greater than 10\n")
}

// 字符串是否为空
if str == "" { ... }
if len(str) == 0 {...}

// 操作系统类型
if runtime.GOOS == "windows" {}
}

switch 结构

package main

import "fmt"

func main() {
var num1 int = 100

switch num1 {
case 98, 99:
fmt.Println("It's equal to 98")
case 100:
fmt.Println("It's equal to 100")
default:
fmt.Println("It's not equal to 98 or 100")
}
}

// --- demo2
switch a, b := x[i], y[j]; {
case a < b: t = -1
case a == b: t = 0
case a > b: t = 1
}

select 结构

切换协程

package main

import (
"fmt"
"time"
)

func main() {
ch1 := make(chan int)
ch2 := make(chan int)

go pump1(ch1)
go pump2(ch2)
go suck(ch1, ch2)

time.Sleep(1e9)
}

func pump1(ch chan int) {
for i := 0; ; i++ {
ch <- i * 2
}
}

func pump2(ch chan int) {
for i := 0; ; i++ {
ch <- i + 5
}
}

func suck(ch1, ch2 chan int) {
for {
select {
case v := <-ch1:
fmt.Printf("Received on channel 1: %d\n", v)
case v := <-ch2:
fmt.Printf("Received on channel 2: %d\n", v)
}
}
}

循环

Break 与 continue

for (range) 结构

for i:=0; i<5; i++ {
for j:=0; j<10; j++ {
println(j)
}
}

// demo2
for i, j := 0, N; i < j; i, j = i+1, j-1 {}

死循环

for { }