qq78707 发表于 2018-9-20 11:14:04

golang 常见疑惑总结

  经常会有一些朋友问go语言的一些问题和疑惑,其实好多问题在官方文档和stackoverflow里都有详细的讲解,只要你肯花时间读一遍官方文档和Effective Go基本上都有找到答案。本文总结一下大家经常问到的一些问题,长期更新。
  代码都在github上, 地址 https://github.com/lpxxn/gocommonquestions

new 和make 的区别
  简单来说,new(T)用于分配内存,返回指向T类型的一个指针,指针的值为T类型的零值
  

    n1 := new(int)  
fmt.Println(n1)
// console the address of n1  
fmt.Println(*n1 == 0) // zero value
  

  
type T struct {
  
I int
  
A string
  
Next *T
  
}
  
n2 := new(T)
  
fmt.Println(n2)
  
fmt.Println(n2.I == 0)
  
fmt.Println(n2.Next == nil)
  
fmt.Println(n2.A == "")
  

  
n3 := new([]int)
  
fmt.Println(n3)
  
fmt.Println(*n3 == nil)
  

  make(T)   只能用于slice、map和channel, 返回非零值的T。
  

    m1 := make([]int, 1)  
fmt.Println(m1)
  
m2 :
= make(mapstring)  
m2[
0] = "abcde"  
m3 :
= make(chan int)  

  
m4 :
= make(chan int, 5)  

  make 返回的是类型本身,new 返回的是指向类型的指针
  相关讲解
  https://stackoverflow.com/questions/9320862/why-would-i-make-or-new
  https://golang.org/doc/effective_go.html#allocation_new
  https://golang.org/ref/spec#The_zero_value

是否需要主动关闭channel
  除非你的程序需要等待channel关闭后做一些操作,不用主动去关闭channel。当没有地方在使用这个channel的时候go的垃圾回收系统会自动回收,如果channel里还有值,但是没有地方引用了,也会被回收。
  下面的小例子就是在等待channel c1和c2关闭后,再做一些事情。  
  

func main() {  
c1 :
= make(chan int, 3)  
go test1(c1)
  

for v := range c1 {  
fmt.Println(v)
  
}
  

  
fmt.Println(
"after close c1 do something")  
c2 :
= make(chan bool)  
go func() {
  
time.AfterFunc(time.Second
* 3, func() {  
close(c2)
  
})
  
}()
  
_, close :
=
页: [1]
查看完整版本: golang 常见疑惑总结