Golang casting a multiple return value to match named result parameter

Viewed 9408

Let's assume I want to define a function with named result parameters, one of which is a string. This function internally calls another function, that returns a bytes representation of such string.

Is there a way to cast the result without using a temporary variable?

func main() {
    out, _ := bar("Example")
    fmt.Println(out)
}

func foo(s string) ([]byte, error) {
    return []byte(s), nil
}

func bar(in string) (out string, err error) {
    // is there a way to assign the result to out
    // casting the value to string in the same line
    // istead of using the tmp variable?
    tmp, err := foo(in)

    if err != nil {
        return "", err
    }
    return string(tmp), nil
}

The idea is that, if that's possible, I could potentially shorten the code to

func bar(in string) (out string, err error) {
    // assuming there is a way to cast out to string
    out, err := foo(in)
    return
}

Does it make sense?

2 Answers

1 line of code won't make a huge difference but having a tmp variable actually sticking around for the entire function is a problem. Temporary variables should be temporary, obviously. For that, you can declare tmp in a new scope.

var s string;
{
    tmp, err := foo(in)
    s = string(tmp)
}

//tmp no longer exists here.
//Other code is not disturbed by a useless tmp variable.

I may be just being stupid here as I am new to Go, I learnt this trick from C, turns out it works for Go as well.

Related