您的位置 首页 golang

Golang Tips

  1. Go的数组只能有固定的长度,传入变量作为数组长度时,只能创建为定义了size的切片
length := 5array := [length]int  // error: non-constant array bound lengtharray := make([]int, length)
  1. Go没有内置的比较整数大笑的方法,需要自己实现
func max(a int, b int) int {    if a >= b {         return a    } else {        return b    }}
  1. Go没有内置的判断array或map是否存在某一个元素的方法,需要通过判断普通的get的error实现
// implement array/list containsfunc contains(array []int, val int) bool {    contains := false    for _, value := range array {        if val == value {            contains = true            break        }    }    return contains}
// implement map containsKeyfunc containsKey(myMap map[int]int, key int) bool {    if _, ok := myMap[key]; ok {        return true    } else {        return false    }}
  1. Golang channel如果不close,遍历会出deadlock error
ans := make(chan string)for i := 0; i<5; i++ {    ans <- "hello"}// fatal error: all goroutines are asleep - deadlock!// need to close it before for loop, or read out fixed numbers of items// close(ans)for n, ok := range ans {    fmt.Println(n)}

文章来源:智云一二三科技

文章标题:Golang Tips

文章地址:https://www.zhihuclub.com/233.shtml

关于作者: 智云科技

热门文章

网站地图