码迷,mamicode.com
首页 > 其他好文 > 详细

go 笔记

时间:2018-05-17 00:50:46      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:i++   code   AC   channel   mat   结构   str   his   class   

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
}

go 笔记

标签:i++   code   AC   channel   mat   结构   str   his   class   

原文地址:https://www.cnblogs.com/baizx/p/9048814.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!