Go: Named return values

In Go return parameters may be named and used as regular variables. When the function returns these variables are implicitly used as return values.

func f() (i int, s string) {
        i = 17
        s = "abc"
        return // same as return i, s

Named return parameters are initialized to their zero values.

The names are not mandatory but can make for good documentation. Correctly used, named return parameters can also help to clarify and clean up the code.

This version of io.ReadFull, taken from Effective Go, uses them well:

func ReadFull(r Reader, buf []byte) (n int, err error) {
    for len(buf) > 0 && err == nil {
        var nr int
        nr, err = r.Read(buf)
        n += nr
        buf = buf[nr:]


Be the first to comment!