switch是很容易理解的,先來(lái)個(gè)代碼,運(yùn)行起來(lái),看看你的操作系統(tǒng)是什么吧。
package main
import (
"fmt"
"runtime"
)
func main() {
fmt.Print("Go runs on ")
switch os := runtime.GOOS; os {
case "darwin":
fmt.Println("OS X.")
case "linux":
fmt.Println("Linux.")
default:
fmt.Printf("%s", os)
}
}
runtime運(yùn)行時(shí)獲取當(dāng)前的操作系統(tǒng),使用GOOS。
還和if for之類(lèi)的習(xí)慣一樣,可以在前面聲明賦值變量。我們就在這里來(lái)獲取操作系統(tǒng)的信息了。
os := runtime.GOOS;
{ } 里的case比較容易理解。操作系統(tǒng)是 "darwin" 就打印"OS X.";操作系統(tǒng)是 "linux" 就打印"Linux";其他的都直接打印系統(tǒng)類(lèi)別。
我用的是windows 10,所以我的運(yùn)行結(jié)果是
Go runs on windows
在go語(yǔ)言的switch中除非以 fallthrough 語(yǔ)句結(jié)束,否則分支會(huì)自動(dòng)終止。
所以修改一下上面的代碼,再運(yùn)行一下
package main
import (
"fmt"
"runtime"
)
func main() {
fmt.Print("Go runs on ")
switch os := runtime.GOOS; os {
case "darwin":
fmt.Println("OS X.")
case "linux":
fmt.Println("Linux.")
case "windows":
fmt.Println("win")
fallthrough
default:
fmt.Printf("%s", os)
}
}
增加了當(dāng)前的系統(tǒng)的case選項(xiàng) "windows",還在這個(gè)分支使用了 fallghrough。
運(yùn)行的結(jié)果就有穿透的效果了。
Go runs on win
windows
如果你再注釋掉 fallthrough,或干脆刪除 fallthrough,再運(yùn)行,就會(huì)發(fā)現(xiàn),那個(gè)穿透的效果沒(méi)有了。
Go runs on win
好吧,我們?cè)侔?fallthrough找回來(lái),并且在下面再加上一個(gè) case 分支,看看效果。
package main
import (
"fmt"
"runtime"
)
func main() {
fmt.Print("Go runs on ")
switch os := runtime.GOOS; os {
case "darwin":
fmt.Println("OS X.")
case "linux":
fmt.Println("Linux.")
case "windows":
fmt.Println("win")
fallthrough
case "gdwing":
fmt.Println("He He!!")
default:
fmt.Printf("%s", os)
}
}
運(yùn)行結(jié)果是
Go runs on win
He He!!
又穿透了,哪怕 "gdwing" 并不是合適的選項(xiàng),也直接穿透運(yùn)行了這個(gè)分支。而且只穿透了 fallthrough 緊鄰的這一個(gè)分支。
現(xiàn)在,對(duì) fallthrough 算是弄明白了。
可以這樣總結(jié):
switch 的條件從上到下的執(zhí)行,當(dāng)匹配成功的時(shí)候停止。如果匹配成功的這個(gè)分支是以fallthrough結(jié)束的,那么下一個(gè)緊鄰的分支也會(huì)被執(zhí)行。
再寫(xiě)一個(gè)判斷距離周六還有多久的程序吧!
package main
import (
"fmt"
"time"
)
func main() {
fmt.Println("When is Saturday?")
today := time.Now().Weekday()
switch time.Saturday {
case today + 0:
fmt.Println("Today.")
case today + 1:
fmt.Println("Tommorrow.")
case today + 2:
fmt.Println("In two days")
default:
fmt.Println("Too far away.")
}
}
運(yùn)行結(jié)果你自己試試看。有耐心的話(huà),每天運(yùn)行一次,看不同的運(yùn)行結(jié)果。愛(ài)動(dòng)手改才是工程師的常規(guī)表現(xiàn),試著改成一個(gè)星期內(nèi)的每一天,看看運(yùn)行結(jié)果。這樣,你就不用等一周了。 嘻嘻!
好了,現(xiàn)在講一下 swith 的沒(méi)有條件的用法。這其實(shí)相當(dāng)于 switch true 一樣。每一個(gè) case 選項(xiàng)都是 bool 表達(dá)式,值為 true 的分支就是被執(zhí)行的分支?;蛘邎?zhí)行 default 。
package main
import (
"fmt"
"time"
)
func main() {
t := time.Now()
switch {
case t.Hour() > 12 && t.Hour() <= 17:
fmt.Println("Morning was passed.")
case t.Hour() > 17:
fmt.Println("Afternoon was passed.")
default:
fmt.Println("Now too early.")
}
}
運(yùn)行結(jié)果
Now too early.
好吧,我現(xiàn)在是凌晨,所以“太早了”。