2026-04-02 02:51:23
在Go语言中,结构体(struct)是一种复合数据类型,用于将多个不同类型的变量组合成一个逻辑实体,常用于描述现实世界中的对象及其属性。以下是关于Go结构体的详细介绍:
1. 结构体的定义结构体通过type关键字定义,格式如下:
type 结构体名 struct { 字段名1 字段类型1 字段名2 字段类型2 // ...}示例:
type Student struct { Name string Id string Age string}2. 结构体的初始化方法一:声明后赋值var student Studentstudent.Name = "陈九礼"student.Age = "9999"student.Id = "1314520"fmt.Println(student) // 输出: {陈九礼 1314520 9999}方法二:直接初始化student := Student{ Name: "陈九礼", Id: "1314520", // 注意逗号 // Age未初始化,默认为零值(空字符串)}fmt.Println(student) // 输出: {陈九礼 1314520 }注意事项:
Go允许为结构体定义关联函数(方法),通过接收者(receiver)绑定到结构体。接收者可以是值类型或指针类型,影响函数内对原对象的修改能力。
方法定义格式func (接收者 结构体类型) 方法名(参数) 返回值 { // 方法体}示例对比指针类型接收者(修改原对象)func (student *Student) setName(name string) { student.Name = name // 直接修改原对象}func main() { student := Student{} student.setName("陈九礼") fmt.Println(student.Name) // 输出: 陈九礼}值类型接收者(操作副本)func (student Student) setAge(age string) { student.Age = age // 修改的是副本}func main() { student := Student{} student.setAge("9999") fmt.Println(student.Age) // 输出: (空值,未修改原对象)}关键区别:
结构体可以嵌套其他结构体,支持显式和隐式字段访问。
显式指定字段名type Person struct { Name string age string}type Student struct { person Person // 显式嵌套 Id string}func main() { student := Student{ person: Person{Name: "陈九礼", age: "9999"}, Id: "1314520", } fmt.Println(student.person.Name) // 输出: 陈九礼}隐式省略字段名(匿名嵌套)type Student struct { Person // 隐式嵌套 Id string}func main() { student := Student{ Person: Person{Name: "陈九礼", age: "9999"}, Id: "1314520", } fmt.Println(student.Name) // 直接访问嵌套字段(无冲突时) fmt.Println(student.Person.Name) // 显式访问亦可}5. 结构体变量的作用域通过合理使用结构体,可以编写出清晰、模块化的Go代码。