关于go:关于golang的逗号ok模式的使用整理

6次阅读

共计 2094 个字符,预计需要花费 6 分钟才能阅读完成。

对于 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 队列, 先发送的 chan 肯定最先被接管
 
    for cc := range ch {fmt.Println(cc)
    }
        // ch <-8 // 此时再往 ch 这个 chan 里发送数据, 就会报错, 因为通道曾经敞开,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 循环的, 此处相似其余语言的 while(true)
    for {
        i, ok := <-ch
        if !ok {fmt.Println("channel closed!")
            break
        }
        fmt.Println(i)
    }
}
 
// 3. 检测是否实现了接口类型
type I interface {
    // 有一个办法的接口 I
    Get() Int}
 
type Int int
 
// Int 类型实现了 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
}
正文完
 0