golang逗號ok模式整合demo
更新時間:2023年11月01日 11:08:48 作者:Peanut
這篇文章主要為大家介紹了golang逗號ok模式整合demo,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
golang的逗號ok模式的使用整理
/* @Time : 2019-02-23 11:49 @Author : Tenlu @File : ok @Software: GoLand */ package main import "fmt" // 逗號ok模式 func main() { useMap() useChan() userType() useType2() } //1.檢測map中是否含有指定key func useMap() { company := map[string]string{"polly": "tencent", "robin": "baidu", "jack": "alibaba", "tenlu": "itech8"} if _, ok := company["toms"]; !ok { fmt.Println("key toms is not exists") } for ck, cv := range company { fmt.Println(ck + "->" + cv) } } // 2. 檢測chan是否關閉 func useChan() { ch := make(chan int, 10) for i := 1; i <= 5; i++ { ch <- i } close(ch) // chan賦值結束,必須關閉通道 elem := <-ch fmt.Println(elem) // 1 // FIFO隊列,先發(fā)送的chan一定最先被接收 for cc := range ch { fmt.Println(cc) } // ch <-8 // 此時再往ch這個chan里發(fā)送數(shù)據(jù),就會報錯,因為通道已經關閉,panic:send on closed channel elem2 := <-ch elem3 := <-ch fmt.Printf("elem2:%d\n", elem2) // 0,因為通道已經關閉 fmt.Printf("elem3:%d\n", elem3) // 0 if _, isClosed := <-ch; !isClosed { fmt.Println("channel closed") } // go是沒有while循環(huán)的,此處類似其他語言的while(true) for { i, ok := <-ch if !ok { fmt.Println("channel closed!") break } fmt.Println(i) } } // 3.檢測是否實現(xiàn)了接口類型 type I interface { // 有一個方法的接口 I Get() Int } type Int int // Int 類型實現(xiàn)了 I 接口 func (i Int) Get() Int { return i } func userType() { var myint Int = 5 var inter I = myint // 變量賦值給接口 val, ok := inter.(Int) fmt.Printf("%v, %v\n", val, ok) // 輸出為:5,true } func useType2() { // chan 類型的空值是 nil,聲明后需要配合 make 后才能使用。 var ch=make(chan interface{},10) ch<-10 ch<-"jack" ch<-map[string]interface{}{"name":"jack","age":11} close(ch) // 此處不close通道,遍歷時則報錯 fmt.Printf("%v\n",<- ch) for c:=range ch { fmt.Printf("for:%v\n",c) fmt.Sprintf("type:%T\n", c) if newValue,ok:=c.(map[string]interface{});ok{ fmt.Printf("type:%s\n",reflect.TypeOf(c)) // 獲取變量類型 // map[string]interface {} if _,ok:=newValue["name"];ok{ for k,v:=range newValue { fmt.Printf("%v->%v,\n",k,v) } } } } fmt.Printf("%v\n",<- ch) // nil } func useType2() { // chan 類型的空值是 nil,聲明后需要配合 make 后才能使用。 var ch=make(chan interface{},10) ch<-10 ch<-"jack" ch<-map[string]interface{}{"name":"jack","age":11} close(ch) // 此處不close通道,遍歷時則報錯 fmt.Printf("%v\n",<- ch) for c:=range ch { fmt.Printf("for:%v\n",c) fmt.Sprintf("type:%T\n", c) if newValue,ok:=c.(map[string]interface{});ok{ fmt.Printf("type:%s\n",reflect.TypeOf(c)) // 獲取變量類型 // map[string]interface {} if _,ok:=newValue["name"];ok{ for k,v:=range newValue { fmt.Printf("%v->%v,\n",k,v) } } } } fmt.Printf("%v\n",<- ch) // nil }
代碼里的注釋很詳細,有需要童鞋可以自行研究實踐下
以上就是golang逗號ok模式整合demo的詳細內容,更多關于golang逗號ok模式的資料請關注腳本之家其它相關文章!