Go 结构体
结构体(struct)把多个字段打包成一个自定义类型,相当于没有继承的"类"。定义:type 名称 struct { 字段 }。(说明:文中的片段代码需放进完整程序里运行)
定义与实例化的多种方式
字段名大写开头表示可被包外访问(导出),小写是包内私有。完整示例:
package main
import "fmt"
type Student struct {
Name string
Age int
Score float64
}
func main() {
var s1 Student // 方式 1:零值初始化
s2 := Student{"小明", 18, 92.5} // 方式 2:按字段顺序给值
s3 := Student{Name: "小红"} // 方式 3:按字段名赋值(推荐)
s4 := &Student{Name: "小刚"} // 方式 4:取地址,结构体指针
fmt.Printf("%+v\n", s1)
fmt.Printf("%+v\n", s2)
fmt.Printf("%+v\n", s3)
fmt.Printf("%+v\n", s4)
}
// 输出:
// {Name: Age:0 Score:0}
// {Name:小明 Age:18 Score:92.5}
// {Name:小红 Age:0 Score:0}
// &{Name:小刚 Age:0 Score:0}
%+v 带字段名打印;没赋值的字段自动取零值,所以方式 3 不用写全。
访问与修改成员
用点号 . 读写字段;结构体指针也直接用 .,Go 会自动解引用:
stu := Student{Name: "小明", Age: 18}
fmt.Println(stu.Name) // 小明
stu.Age = 19 // 修改字段
fmt.Println(stu.Age) // 19
p := &Student{Name: "小红", Age: 17}
p.Age = 18 // 等价于 (*p).Age = 18
fmt.Println(p.Age) // 18
嵌套结构体
结构体可以包含其他结构体(组合代替继承)。匿名嵌套时,内层字段会被"提升",可省略外层直接访问:
type Address struct{ City string }
type Person struct {
Name string
Address // 匿名嵌套:字段名就是类型名
}
p := Person{Name: "小明", Address: Address{City: "上海"}}
fmt.Println(p.Address.City) // 上海
fmt.Println(p.City) // 提升字段,可直接访问
方法接收者(简述)
带接收者的函数叫方法。接收者是值,方法内改不了原对象;接收者是指针才能修改字段:
type Student struct{ Name string; Age int }
func (s Student) SayHi() { fmt.Println("你好,我是", s.Name) } // 值接收者
func (s *Student) Birthday() { s.Age++ } // 指针接收者
// stu := Student{Name: "小明", Age: 18}
// stu.SayHi(); stu.Birthday() → Age 变成 19
小结:结构体加方法就是 Go 的"面向对象"——没有类与继承,用组合代替继承;想改原对象字段就选指针接收者。