• go 笔记


    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
    }
    
  • 相关阅读:
    SWT中如何居中显示?
    项目一 默认构造函数和带参数的构造函数
    解决ubuntu中java1.6显示中文乱码问题
    网络程序为什么要处理SIGPIPE
    SQL 数据类型大全
    poj1275 差分约束
    Oracle分组
    Android利用ViewPager实现滑动广告板
    扩展spring mvc的拦截器,实现AOP的环绕增加效果
    [Ext.Net]GridPanel之存储过程分页Sql版本
  • 原文地址:https://www.cnblogs.com/baizx/p/9048814.html
Copyright © 2020-2023  润新知