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

时间:2012-12-06 11:06:51

标签: go

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

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

在上面的例子中是否可以避免丑陋的“节点(节点)”?有没有更惯用的方法来强制编译器将节点视为节点而不是int?

2 个答案:

答案 0 :(得分:3)

没有什么比这更优雅。您可以定义一个中间变量

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

或者您可以定义包装函数

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

但我不认为有任何单行技巧。你这样做的方式似乎很好。在Go中,这里和那里仍然有一点口吃。

答案 1 :(得分:1)

没有。转换转换(可转换)表达式。如果函数只有一个返回值,则函数的返回值是一个术语(因此可能是一个可转换的表达式)。可以找到符合转换条件的其他限制here