Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang casting a multiple return value to match named result parameter

Tags:

casting

go

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?

like image 910
Simone Carletti Avatar asked Dec 07 '13 18:12

Simone Carletti


1 Answers

There is no way to cast in a multiple return from a function. That doesn't mean you can't shorten your code though. http://play.golang.org/p/bf4D71_rZF If you don't care about the error then just cast the variable in your inline return

like image 119
Jeremy Wall Avatar answered Sep 19 '22 11:09

Jeremy Wall