Go 语言数据类型

基本类型、零值、类型大小、以及 string 与 byte/rune 的关系。

Beginner
Key PointsGo 的类型是强类型且不隐式转换;每种类型都有确定的零值。

分类

KindTypesZero value
布尔boolfalse
整数int int8 int16 int32 int640
无符号uint uint8 uint16 uint32 uint64 uintptr0
浮点float32 float640
复数complex64 complex1280+0i
字符串string""
字符byte(uint8)rune(int32)0

零值

Go
var (
	i  int
	f  float64
	s  string
	b  bool
	p  *int
	sl []int
	m  map[string]int
)

fmt.Printf("%d %v %q %v %v %v %v\n", i, f, s, b, p, sl, m)
fmt.Println(sl == nil, m == nil, p == nil)
Output
0 0 "" false <nil> [] map[]
true true true

A var declaration always has a defined value — there is no "uninitialised" state. That is one reason Go needs no constructors.

string 与 byte / rune

Go
s := "Go语言"

fmt.Println(len(s))                  // 字节数
fmt.Println(len([]rune(s)))          // 字符数

for i := 0; i < len(s); i++ {
	fmt.Printf("%d ", s[i])          // 逐字节
}
fmt.Println()

for _, r := range s {
	fmt.Printf("%c ", r)             // 逐字符
}
fmt.Println()
Output
8
4
71 111 232 175 173 232 168 128
G o 语 言

len(s) counts bytes: the two CJK characters take 3 bytes each, hence 8 rather than 6. Use range to iterate characters — it decodes UTF-8 into runes.

类型不隐式转换

Go
var a int32 = 1
var b int64 = 2

// fmt.Println(a + b)     // 编译错误:mismatched types
fmt.Println(int64(a) + b) // 必须显式转换

var f float64 = 1.9
fmt.Println(int(f))       // 截断,不是四舍五入 → 1
Output
3
1
int is 32-bit on 32-bit platforms and 64-bit on 64-bit ones. For cross-platform consistency or wire protocols, **write int32/int64 explicitly**.

Friends & Partners