Passing parameters to function closure

前端 未结 2 1779
别跟我提以往
别跟我提以往 2020-12-29 05:33

I\'m trying to understand the difference in Go between creating an anonymous function which takes a parameter, versus having that function act as a closure. Here is an examp

2条回答
  •  星月不相逢
    2020-12-29 06:02

    When to use parameters

    Definitely the first form is preferred if you plan to change the value of the variable which you don't want to observe in the function.

    This is the typical case when the anonymous function is inside a for loop and you intend to use the loop's variables, for example:

    for i := 0; i < 10; i++ {
        go func(i int) {
            fmt.Println(i)
        }(i)
    }
    

    Without passing the variable i you might observe printing 10 ten times. With passing i, you will observe numbers printed from 0 to 9.

    When not to use parameters

    If you don't want to change the value of the variable, it is cheaper not to pass it and thus not create another copy of it. This is especially true for large structs. Although if you later alter the code and modify the variable, you may easily forget to check its effect on the closure and get unexpected results.

    Also there might be cases when you do want to observe changes made to "outer" variables, such as:

    func GetRes(name string) (Res, error) {
        res, err := somepack.OpenRes(name)
        if err != nil {
            return nil, err
        }
    
        closeres := true
        defer func() {
            if closeres {
                res.Close()
            }
        }()
    
        // Do other stuff
        if err = otherStuff(); err != nil {
            return nil, err // res will be closed
        }
    
        // Everything went well, return res, but
        // res must not be closed, it will be the responsibility of the caller
        closeres = false
    
        return res, nil // res will not be closed
    }
    

    In this case the GetRes() is to open some resource. But before returning it other things have to be done which might also fail. If those fail, res must be closed and not returned. If everything goes well, res must not be closed and returned.

提交回复
热议问题