假设我想要定义一个带有命名结果参数的函数,其中一个是一个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)
是否有意义?