英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论