Golang常见编程问题
--语言简单
func CopyFile (dst, src string) (w int64, err error) { srcFile, err := os.Open (src) defer srcFile.Close () if err != nil { return } //using srcFile to do sth return }
- 函数可以返回多个值
- 推荐将 error 作为最后一一个返回值
- Defer , 常用用来做资源清理、记录执行行时间等
--go range
values := []string{"a", "b", "c"} for _, v := range values { go func() { fmt.Println(v) }() }
--goroutine 通信
- 消息机制基于通信来共享。
- go中goroutine之间是通chan通讯的,chan的处理了不少用到select
- 当多个receiver channel都处于就绪状态时,激活的channel是随机的。
package main import ( "fmt" "runtime" "time" ) func main() { runtime.GOMAXPROCS(runtime.NumCPU()) ch := make(chan int,1024) go func(ch chan int) { for{ val := <-ch fmt.Println("val:",val) } }(ch) tick :=time.NewTicker(1 * time.Second) for i := 0;i <30;i++{ select { case ch <-i: case <-tick.C: fmt.Println("1 Second") } time.Sleep(200 * time.Millisecond) } close(ch) tick.Stop() } //val: 0 //val: 1 //val: 2 //val: 3 //val: 4 //val: 5 //val: 6 //1 Second //val: 8 //val: 9 //1 Second //val: 11 //val: 12 //val: 13 //val: 14 //1 Second //val: 16 //val: 17 //val: 18 //val: 19 //val: 20 //val: 21 //val: 22 //val: 23 //val: 24 //1 Second //val: 26 //val: 27 //val: 28 //val: 29
往 chan 中放数据时,如果缓冲区已经满那么将 block
以下方方式可以试探往 chan 放数据
func putSignal(ch chan struct{}, sign struct{}) (ok bool) { select { case ch <- sign: ok = true default:// 省略了会 block } } return
cpu 消耗问题
select 滥用用引发