Go語(yǔ)言學(xué)習(xí)之Switch語(yǔ)句的使用
基本語(yǔ)法
在講述if-else時(shí)已經(jīng)提到,如果有多個(gè)判斷條件,Go語(yǔ)言中提供了Switch-Case的方式。如果switch后面不帶條件相當(dāng)于switch true
// Convert hexadecimal character to an int value
switch {
case '0' <= c && c <= '9':
return c - '0'
case 'a' <= c && c <= 'f':
return c - 'a' + 10
case 'A' <= c && c <= 'F':
return c - 'A' + 10
}
return 0
fallthrough使用方法
默認(rèn)情況下,case滿足執(zhí)行后會(huì)進(jìn)行break,后面case即使?jié)M足條件也不再循環(huán),如果想繼續(xù)執(zhí)行,則需要添加fallthrough,
package main
import "fmt"
func main() {
i := 3
switch i {
case i > 0:
fmt.Println("condition 1 triggered")
fallthrough
case i > 2:
fmt.Println("condition 2 triggered")
fallthrough
default:
fmt.Println("Default triggered")
}
}
此時(shí)所有的case都會(huì)被執(zhí)行
condition 1 triggered
condition 2 triggered
Default triggered
多條件匹配
如果同一個(gè)條件滿足,也可以這樣羅列到同一條件,相當(dāng)于或條件
switch i {
case 0, 1:
f()
default:
g()
}
判斷接口(interface)類型
空接口
后面我們會(huì)講到接口,通過(guò)switch可以對(duì)type進(jìn)行判斷,獲取接口的真實(shí)類型。
package main
import "fmt"
func main() {
var value interface{}
switch q:= value.(type) {
case bool:
fmt.Println("value is of boolean type")
case float64:
fmt.Println("value is of float64 type")
case int:
fmt.Println("value is of int type")
default:
fmt.Printf("value is of type: %T", q)
}
}在上面的例子中,我們定義了一個(gè)空接口
var value interface{}
同時(shí)使用switch來(lái)判斷類型
switch q:= value.(type) {
由于空接口沒(méi)有內(nèi)容,所以類型為nil,觸發(fā)了default
value is of type: <nil>
獲取實(shí)際類型
我們對(duì)上面的例子進(jìn)行改造,同時(shí)讓空接口擁有實(shí)際的值,再來(lái)看看執(zhí)行的效果
package main
import "fmt"
func valueType(i interface{}) {
switch q:= i.(type) {
case bool:
fmt.Println("value is of boolean type")
case float64:
fmt.Println("value is of float64 type")
case int:
fmt.Println("value is of int type")
default:
fmt.Printf("value is of type: %T\n", q)
}
}
func main() {
person := make(map[string]interface{}, 0)
person["name"] = "Alice"
person["age"] = 21
person["height"] = 167.64
fmt.Printf("%+v\n", person)
for _, value := range person {
valueType(value)
}
}
這里有幾個(gè)還沒(méi)有講到的知識(shí)點(diǎn):
- 函數(shù)的定義方法
- 定義了一個(gè)map,但是值的類型為空接口,意思就是可以是任何類型的值,這在接口章節(jié)還會(huì)詳細(xì)講解,所以大家看到這里不要糾結(jié),繼續(xù)往下看
- 賦值時(shí),特意給value不同的類型, string/int/float類型
最后通過(guò)循環(huán)將變量傳給valueType函數(shù),看看程序輸出什么結(jié)果
map[age:21 height:167.64 name:Alice]
value is of type: string
value is of int type
value is of float64 type
到此這篇關(guān)于Go語(yǔ)言學(xué)習(xí)之Switch語(yǔ)句的使用的文章就介紹到這了,更多相關(guān)Go語(yǔ)言 Switch語(yǔ)句內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
使用Go語(yǔ)言進(jìn)行安卓開(kāi)發(fā)的詳細(xì)教程
本文將介紹如何使用Go語(yǔ)言進(jìn)行安卓開(kāi)發(fā),我們將探討使用Go語(yǔ)言進(jìn)行安卓開(kāi)發(fā)的優(yōu)點(diǎn)、準(zhǔn)備工作、基本概念和示例代碼,通過(guò)本文的學(xué)習(xí),你將了解如何使用Go語(yǔ)言構(gòu)建高效的安卓應(yīng)用程序,需要的朋友可以參考下2023-11-11

