【golog】我的go學與思6

其他類型

正文

類型轉化

var i int = 42
var f float64 = float64(i)
var u uint = uint(f)

縮寫爲:

i := 42
f := float64(i)
u := uint(f)

反正,go只提供顯示類型轉化。c++是又隱式類型轉化的比如各種類型數字都是往double的方向(不是轉化爲double)轉化的。這樣計組的時候我們學過:uint和int的比較會出問題,其實就是因爲這種隱式轉化的風險。

類型推導

package main

import "fmt"

func main() {
	v := 42           // change me!
	f := 3.142        // float64
	g := 0.867 + 0.5i // complex128
	fmt.Printf("v is of type %T\n", v)
	fmt.Printf("f is of type %T\n", f)
	fmt.Printf("g is of type %T\n", g)
}

// 輸出
v is of type int
f is of type float64
g is of type complex128

這就回答了前面我的好奇,果然go是默認數字爲int然後再動態分配到,不會因爲42小而分配int8這種恰好滿足的類型。

常量(constants)

就是用const修飾變量名就行。

不能修飾臨時變量。

import也有一個很好看的寫法:

package main

import "fmt"

const (
	// Create a huge number by shifting a 1 bit left 100 places.
	// In other words, the binary number that is 1 followed by 100 zeroes.
	Big = 1 << 100
	// Shift it right again 99 places, so we end up with 1<<1, or 2.
	Small = Big >> 99
)

func needInt(x int) int { return x*10 + 1 }
func needFloat(x float64) float64 {
	return x * 0.1
}

func main() {
	fmt.Println(needInt(Small))
	fmt.Println(needFloat(Small))
	fmt.Println(needFloat(Big))
}

Q: 很奇怪,這裏顯然如果Small的類型確定是在const修飾的時候的話,那麼顯然這裏至少發生了一次隱式類型轉化:Small傳參給函數的時候。go語言是不允許隱式傳參的,那麼推測這個類型確定時機實在使用的時候。

來實踐一下,go語言不確定類型是不能當右值給另一個不確定類型做類型推導的。那麼:

package main

import "fmt"

const (
    Big = 1 << 100
	Small = Big >> 99
)

func main() {
	a := Samll
	fmt.Println(a)
}

是可以是運行的.

fmt.Println(Big),報錯:constant 1267650600228229401496703205376 overflows int

fmt.Println(Big*0.1),輸出:1.2676506002282295e+29

這是不是說明,go其實還是有隱式類型轉化的,那就會有類型推導安全問題。這個以後再說吧。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章