Skip to content

Go语言中的数据类型分类 #113

Description

@MagicalBridge

1. 基本数据类型(Primitive Data Types)

1.1 整数类型

  • int:平台相关,32位或64位。
  • int8int16int32int64:固定位数的有符号整数。
  • uint:平台相关的无符号整数。
  • uint8uint16uint32uint64:固定位数的无符号整数。
  • byteuint8的别名,用于表示字节。
  • runeint32的别名,用于表示Unicode码点。
varaint=42varbint8=127varcuint=255vardbyte='A'// 等同于 uint8varerune='你'// 等同于 int32

1.2 浮点数类型

  • float32:32位浮点数。
  • float64:64位浮点数。
varf1float32=3.14varf2float64=3.141592653589793

1.3 复数类型

  • complex64:由两个float32组成的复数。
  • complex128:由两个float64组成的复数。
varc1complex64=1+2ivarc2complex128=3+4i

1.4 布尔类型

  • bool:取值为truefalse
varisTruebool=truevarisFalsebool=false

1.5 字符串类型

  • string:不可变的字节序列。
varsstring="Hello, Go!"

2. 复合数据类型(Composite Data Types)

2.1 数组(Array)

  • 固定长度的序列,元素类型相同。
vararr [3]int= [3]int{1, 2, 3}

2.2 切片(Slice)

  • 动态长度的序列,基于数组封装。
vars []int= []int{1, 2, 3}
s=append(s, 4) // 动态添加元素

2.3 映射(Map)

  • 键值对集合,键和值可以是任意类型。
varmmap[string]int=map[string]int{"age": 25, "height": 180}

2.4 结构体(Struct)

  • 由一组字段组成的复合类型。
typePersonstruct {
NamestringAgeint
}
varpPerson=Person{Name: "Alice", Age: 30}

2.5 指针(Pointer)

  • 存储变量的内存地址。
varxint=10varp*int=&x// p指向x的地址

3. 接口类型(Interface Type)

3.1 接口(Interface)

  • 定义一组方法签名,由具体类型实现。
typeSpeakerinterface {
Speak() string
}
typeDogstruct{}
func (dDog) Speak() string {
return"Woof!"
}
varsSpeaker=Dog{}
fmt.Println(s.Speak()) // 输出: Woof!

4. 函数类型(Function Type)

4.1 函数(Function)

  • 函数可以作为变量或参数传递。
typeMyFuncfunc(int) intvarfMyFunc=func(xint) int {
returnx*x
}
fmt.Println(f(5)) // 输出: 25

5. 通道类型(Channel Type)

5.1 通道(Channel)

  • 用于goroutine之间的通信。
ch:=make(chanint)
gofunc() {
ch<-42// 发送数据
}()
value:=<-ch// 接收数据fmt.Println(value) // 输出: 42

6. 自定义类型(Custom Type)

6.1 类型别名(Type Alias)

  • 为现有类型创建别名。
typeMyIntintvarxMyInt=10

6.2 结构体类型(Struct Type)

  • 自定义结构体类型。
typePointstruct {
X, Yint
}
varpPoint=Point{X: 1, Y: 2}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions