iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 4
1

golang 型別,其實和絕大多數的靜態強型別的語言,沒什麼兩樣,而且他是c like的語言,所以如果對 C 稍微有點概念的人,會覺得 golang 非常的親切,接下來我們就來介紹他的型別

數字型別

下面這份參照自官網

uint8       the set of all unsigned  8-bit integers (0 to 255)
uint16      the set of all unsigned 16-bit integers (0 to 65535)
uint32      the set of all unsigned 32-bit integers (0 to 4294967295)
uint64      the set of all unsigned 64-bit integers (0 to 18446744073709551615)

int8        the set of all signed  8-bit integers (-128 to 127)
int16       the set of all signed 16-bit integers (-32768 to 32767)
int32       the set of all signed 32-bit integers (-2147483648 to 2147483647)
int64       the set of all signed 64-bit integers (-9223372036854775808 to 9223372036854775807)

float32     the set of all IEEE-754 32-bit floating-point numbers
float64     the set of all IEEE-754 64-bit floating-point numbers

complex64   the set of all complex numbers with float32 real and imaginary parts
complex128  the set of all complex numbers with float64 real and imaginary parts

byte        alias for uint8
rune        alias for int32

下面我們來看一下:

package main

import (
	"fmt"
)

func main() {
	var (
		a float64 = 1
		b float64 = 1
		c float64 = 1.2
	)
	d:=a+b
	fmt.Println(d)
	fmt.Println(c+d)
}

https://play.golang.org/p/vF1uzxwd-8j

在這邊另外介紹一個東西叫做強轉型,如果float32跟float64要做運算的話,正常情況這兩個型別是無法直接做運算,所以float32要做強轉,在這邊建議,一般是建議小type轉成大type,而不要大type轉小type,以免造成數值失真,範例如下:

package main

import (
	"fmt"
)

func main() {
	var (
		a float64 = 1
		b float32 = 1
		c float64 = 1.2
	)
	d := a + float64(b)
	fmt.Println(d)
	fmt.Println(c + d)
}

https://play.golang.org/p/BFABBWaP-Hf

字串型別

字串來說非常容易,就是以雙引號包起來的都叫做字串,這邊範例介紹一下,如何簡易的做字串串接:

package main

import (
	"fmt"
)

func main() {
	var (
		a string = "Hello"
		b string = "World"
	)
	d := a+b
	fmt.Println(d)
}

https://play.golang.org/p/2SUk-UlSSRm

上述這個字串串接的方法不是 best practice ,原因在於這種字串串法,會額外產生一塊記憶體空間,有興趣研究的可以參考Efficient String Concatenation in Go的各式串接方式

布林型別

範例:

package main

import (
	"fmt"
)

func main() {
	var (
		a bool = true
		b bool = false
	)

	fmt.Println(a && b)
	fmt.Println(a || b)
}

https://play.golang.org/p/6eirvfO2aVs


上一篇
如何宣告變數
下一篇
Golang 邏輯控制
系列文
Go劍復國-30天導入Golang30

尚未有邦友留言

立即登入留言