在Go语言中,是否可以对函数的多个返回值进行类型转换?

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

In Go, is it possible to perform type conversions on the multiple return values of a function?

问题

type Node int
node, err := strconv.Atoi(num)

Foo(Node(node)) // Foo接受一个Node,而不是一个int

在上面的例子中,有没有办法避免丑陋的"Node(node)"?有没有更符合惯用法的方法来强制编译器将node视为Node而不是int?

英文:
type Node int
node, err := strconv.Atoi(num)

Foo(Node(node))  // Foo takes a Node, not an int

Is it possible to avoid the ugly "Node(node)" in the above example? Is there a more idiomatic way to force the compiler to consider node a Node and not an int?

答案1

得分: 3

没有什么特别优雅的方法。你可以定义一个中间变量:

n, err := strconv.Atoi(num)
node := Node(n)

或者你可以定义一个包装函数:

func parseNode(s string) Node {
    n, err := strconv.Atoi(num)
    return Node(n)
}

但是我不认为有任何一行代码的技巧。你现在的做法看起来还不错。在Go语言中仍然有一些地方会有一些卡顿。

英文:

Nothing really elegant. You could define an intermediate variable

n, err := strconv.Atoi(num)
node := Node(n)

or you could define a wrapper function

func parseNode(s string) Node {
    n, err := strconv.Atoi(num)
    return Node(n)
}

but I don't think there are any one-line tricks. The way you are doing it seems fine. There is still a little stuttering here and there in Go.

答案2

得分: 1

No. Conversion converts an (convertible) expression. Return value of a function is a term (and thus possibly a convertible expression) iff the function has exactly one return value. Additional restrictions on the expression eligible for conversion can be found here.

英文:

No. Conversion converts an (convertible) expression. Return value of a function is a term (and thus possibly a convertible expression) iff the function has exactly one return value. Additional restrictions on the expression eligible for conversion can be found here.

huangapple
  • 本文由 发表于 2012年12月6日 19:06:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/13742285.html
匿名

发表评论

匿名网友

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

确定