2015-07-11 103 views
3

我一直在玩弄去,我碰到了圍棋的(非?)功能,同時運行下面的代碼:爲什麼我必須將整數轉換爲float64才能匹配?

a := 1  //int 
b := 1.0 //float64 

c := a/b //should be float64 

當我跑這我得到以下運行時錯誤:

invalid operation: a/b (mismatched types int and float64) 

我認爲GoLang應該和類型推斷相當不錯。爲什麼我需要寫:

c := float64(a)/b //float64 

一般來說,給定兩個數字類型,c應該被推斷爲包含兩者的最小類型。我不認爲這是一個疏忽,所以我只是想弄明白爲什麼這個行爲是決定的。僅出於可讀性的原因?或者,我的建議行爲會在語言或其他方面造成某種邏輯不一致?

+0

另請參見[圍棋博客:常量(https://blog.golang.org/constants)。在你的具體例子中,使'a'成爲一個無類型常量(即'const i = 1')將避免顯式轉換。 –

+0

@DaveC是的,我昨天晚上讀到了。這是一個很好的閱讀,併爲我清除了一些細節。 – breeden

回答

5

這在FAQ中提到:Why does Go not provide implicit numeric conversions?

The convenience of automatic conversion between numeric types in C is outweighed by the confusion it causes. When is an expression unsigned? How big is the value? Does it overflow? Is the result portable, independent of the machine on which it executes?
It also complicates the compiler.

這就是爲什麼你需要:

  • 要麼做一個明確的type conversion

    c := float64(a)/b 
    
  • 或使用var float64

    var a, b float64 
    a = 1  //float64 
    b = 1.0 //float64 
    c := a/b 
    
+0

謝謝!我不認爲自動轉換數字類型會破壞嚴格靜態類型的語言,如C所示。我沒有考慮到無符號和有符號溢出問題的複雜性。 – breeden

+1

@breeden是的,你可以看到該語言的創建者之一Go(Rob Pike)對此有何評論:http://blog.golang.org/constants:「設計Go時,我們決定避開這個雷區通過強制不混合數字類型,如果你想添加我和你,你必須明確你想要的結果是什麼。「 – VonC

相關問題