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

huangapple go评论156阅读模式
英文:

Golang casting a multiple return value to match named result parameter

问题

假设我想定义一个带有命名结果参数的函数,其中一个参数是一个字符串。这个函数内部调用另一个函数,该函数返回该字符串的字节表示。

有没有一种方法可以在不使用临时变量的情况下进行类型转换?

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) {
    // 是否有一种方法可以将结果赋值给out,
    // 在同一行中将值转换为字符串,
    // 而不是使用临时变量?
    tmp, err := foo(in)

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

这个想法是,如果可能的话,我可以将代码缩短为:

func bar(in string) (out string, err error) {
    // 假设有一种方法可以将out转换为字符串
    out, err := foo(in)
    return
}

这样是否有意义?

英文:

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?

答案1

得分: 10

从函数中返回多个值时,没有办法进行类型转换。但这并不意味着你不能简化你的代码。如果你不关心错误,那么只需在内联返回中进行变量转换即可。

英文:

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

答案2

得分: 2

1行代码不会有太大的区别,但是在整个函数中保留一个tmp变量是一个问题。临时变量应该是临时的,显然。为此,您可以在一个新的作用域中声明tmp

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

//tmp在这里不再存在。
//其他代码不会受到无用的tmp变量的干扰。

我可能只是太蠢了,因为我刚接触Go,我从C中学到了这个技巧,结果在Go中也适用。

英文:

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.

huangapple
  • 本文由 发表于 2013年12月8日 02:46:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/20445122.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定