分享
Golang Tips
Lyudmilalala · · 1157 次点击 · · 开始浏览这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。
- Go的数组只能有固定的长度,传入变量作为数组长度时,只能创建为定义了size的切片
length := 5
array := [length]int // error: non-constant array bound length
array := make([]int, length)
- Go没有内置的比较整数大笑的方法,需要自己实现
func max(a int, b int) int {
if a >= b {
return a
} else {
return b
}
}
- Go没有内置的判断array或map是否存在某一个元素的方法,需要通过判断普通的get的error实现
// implement array/list contains
func contains(array []int, val int) bool {
contains := false
for _, value := range array {
if val == value {
contains = true
break
}
}
return contains
}
// implement map containsKey
func containsKey(myMap map[int]int, key int) bool {
if _, ok := myMap[key]; ok {
return true
} else {
return false
}
}
- 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)
}
有疑问加站长微信联系(非本文作者)
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
关注微信1157 次点击
添加一条新回复
(您需要 后才能回复 没有账号 ?)
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码` - 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传
收入到我管理的专栏 新建专栏
- Go的数组只能有固定的长度,传入变量作为数组长度时,只能创建为定义了size的切片
length := 5
array := [length]int // error: non-constant array bound length
array := make([]int, length)
- Go没有内置的比较整数大笑的方法,需要自己实现
func max(a int, b int) int {
if a >= b {
return a
} else {
return b
}
}
- Go没有内置的判断array或map是否存在某一个元素的方法,需要通过判断普通的get的error实现
// implement array/list contains
func contains(array []int, val int) bool {
contains := false
for _, value := range array {
if val == value {
contains = true
break
}
}
return contains
}
// implement map containsKey
func containsKey(myMap map[int]int, key int) bool {
if _, ok := myMap[key]; ok {
return true
} else {
return false
}
}
- 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)
}