您现在的位置是:首页 > 文章详情

go 笔记

日期:2018-05-15点击:297

go 笔记

defer

defer 的参数绑定是在 defer 时,而不是在执行时,和 go 是一样的。

for i := 0; i < 5; i++ { defer fmt.Printf("%d ", i) }

会输出4 3 2 1 0

make && new

make 只能应用于 slice,map,channel,返回的不是指针。
以 slice 为例,一个 slice 是引用 copy,但是每个 slice 结构体战三个字。

channel

range 用法,以及如何idiomatic的使用 closure

func handle(queue chan *Request) { for r := range queue { process(r) } } func Serve(queue chan *Request) { for req := range queue { req := req // Create new instance of req for the goroutine. sem <- 1 go func() { process(req) <-sem }() } }

panic

panic可以用作复杂的错误处理,但是如果是用作错误处理,不要把 panic 暴露到包外。

Useful though this pattern is, it should be used only within a package. Parse turns its internal panic calls into error values; it does not expose panics to its client. That is a good rule to follow.

 // error is a method of *Regexp that reports parsing errors by // panicking with an Error. func (regexp *Regexp) error(err string) { panic(Error(err)) } // Compile returns a parsed representation of the regular expression. func Compile(str string) (regexp *Regexp, err error) { regexp = new(Regexp) // doParse will panic if there is a parse error. defer func() { if e := recover(); e != nil { regexp = nil // Clear return value. err = e.(Error) // Will re-panic if not a parse error. } }() return regexp.doParse(str), nil }
原文链接:https://yq.aliyun.com/articles/640353
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章