Reputation: 4281
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?
Upvotes: 1
Views: 175
Reputation: 91253
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.
Upvotes: 1
Reputation: 28355
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.
Upvotes: 3