type Node int
node, err := strconv.Atoi(num)
Foo(Node(node)) // Foo takes a Node, not an int
在上面的例子中可以避免醜陋的「節點(節點)」嗎?有沒有更強烈的方式來強制編譯器考慮Node節點而不是int?在Go中,是否可以對函數的多個返回值執行類型轉換?
type Node int
node, err := strconv.Atoi(num)
Foo(Node(node)) // Foo takes a Node, not an int
在上面的例子中可以避免醜陋的「節點(節點)」嗎?有沒有更強烈的方式來強制編譯器考慮Node節點而不是int?在Go中,是否可以對函數的多個返回值執行類型轉換?
沒什麼真正的優雅。你可以定義一箇中間變量
n, err := strconv.Atoi(num)
node := Node(n)
,或者你可以定義一個包裝函數
func parseNode(s string) Node {
n, err := strconv.Atoi(num)
return Node(n)
}
,但我不認爲有任何一個在線的技巧。你這樣做的方式似乎很好。 Go的各處還有一些口吃。
否轉換轉換(可轉換)表達式。如果函數只有一個返回值,則函數的返回值是一個項(因此可能是一個可轉換表達式)。對符合轉換條件的表達式的其他限制可以在here找到。
我覺得上面的包裝函數不會編譯未使用的'err'的b/c。 – zzzz
沒錯,但最初的例子也不是一個完整的工作例子。顯然這兩個地方都遺漏了東西。 – Sonia