Golang转换多个返回值以匹配命名结果参数

Sim*_*tti 9 casting go

假设我想要定义一个带有命名结果参数的函数,其中一个是一个string.此函数在内部调用另一个函数,该函数返回此类字符串的字节表示形式.

有没有办法在不使用临时变量的情况下转换结果?

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
}
Run Code Online (Sandbox Code Playgroud)

我的想法是,如果可能的话,我可能会缩短代码

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

是否有意义?

Jer*_*all 9

无法从函数中转换多次返回.这并不意味着你不能缩短你的代码.http://play.golang.org/p/bf4D71_rZF如果您不关心错误,那么只需在内联返回中转换变量