dongyuan2652 2017-10-12 20:48
浏览 71
已采纳

Golang日志函数返回参数

I would like to log a function's return values. The "smartest" thing I could come up with is wrapping my actual function body in a closure.

func foo(a int, b int) (int, error) {
    c, err := func (a int, b int) (int, error) {
        //...
        return c, err
    }(a, b)

    fmt.Printf("%v %v %v %v", a, b, c, err)

    return c, err
}

Is there a way to accomplish this with less boilerplate?

  • 写回答

3条回答 默认 最新

  • douliang6563 2017-10-13 03:07
    关注

    Maybe I misunderstood your question, but what about:

    package main
    
    import (
        "log"
    )
    
    func foo(a, b int) (c int, err error) {
        defer func() {log.Printf("%v %v %v %v", a, b, c, err)}()
        c = a + b
        return c, nil
    }
    
    
    func main() {
        foo(1, 3)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?