中级阶段

结构体与方法

Go 没有类和继承,只有结构体和方法。理解值接收者与指针接收者的区别、嵌入如何实现组合、以及何时该用哪种,才能写出既不浪费内存又不触发 nil 陷阱的代码。

结构体定义#

go
type User struct {
	ID        int64
	Name      string
	Email     *string   // 指针表示「可能没有」
	Age       uint8
	CreatedAt time.Time
	Tags      []string
	Meta      map[string]string
}

字段按对齐规则排列可以省内存(Go 1.19+ 有 fieldalignment 检查工具)。

bash
go vet -all ./...
# 或用 golang.org/x/tools/go/analysis/passes/fieldalignment

结构体可以嵌套:

go
type Address struct {
	City string
	Zip  string
}

type Employee struct {
	Address // 匿名嵌入
	Name    string
}

值接收者 vs 指针接收者#

这是 Go 里最重要的一个设计决策。

go
type Counter struct {
	n int
}

func (c Counter) Get() int {   // 值接收者:复制一份
	return c.n
}

func (c *Counter) Inc() {      // 指针接收者:操作原对象
	c.n++
}

规则:

值接收者指针接收者
操作对象副本原对象
能否修改字段否能
大结构体的开销每次调用都复制只复制指针
nil 安全永远安全调用前必须非 nil

混用的陷阱#

go
func (c Counter) Get() int { return c.n }
func (c *Counter) Inc() { c.n++ }

c := Counter{}
c.Inc()
fmt.Println(c.Get()) // 0!

c.Inc() 自动取地址(因为 c 是可寻址变量),所以修改生效了;但 c.Get() 是值接收者,复制了一份,返回 0。

Go 的建议:

  1. 同一个类型的所有方法统一用一种接收者。要么全值,要么全指针。混用最容易出上面的 bug。
  2. 类型包含 sync.Mutex 等不可复制的东西时,必须用指针接收者。
  3. 结构体较大(经验上超过 3~4 个字长)时用指针接收者,避免复制开销。
  4. 小而不可变的值类型(如 time.Time、Point)用值接收者是合理的。

标准库的 go vet 有一项 copylocks 检查,能发现「复制了带锁的值类型」。

go
type Bad struct {
	mu sync.Mutex
}

func (b Bad) Do() { b.mu.Lock() } // go vet: passes lock by value

为什么 time.Time 用值接收者#

time.Time 内部有 *Location 指针和 wall/ext/loc 三个字段,加起来 24 字节,属于小类型,可以放心复制。而它的 Location 指针指向只读数据,复制是安全的。

构造器#

Go 没有构造函数,用返回指针的普通函数约定俗成地当构造函数用:

go
func NewUser(id int64, name, email string) *User {
	return &User{
		ID:    id,
		Name:  name,
		Email: &email,
	}
}

约定:

  • 返回 *User 而不是 User,避免调用方拿到一份「改不动」的副本
  • 构造器里做参数校验,失败返回 (nil, error):
go
func NewUser(id int64, name string) (*User, error) {
	if id <= 0 {
		return nil, fmt.Errorf("用户 ID 必须为正数: %d", id)
	}
	if name == "" {
		return nil, errors.New("用户名不能为空")
	}
	return &User{ID: id, Name: name}, nil
}

New 开头还是 NewXxx#

标准库习惯是 NewReader、NewClient——包名已经表明了类型名,所以省略 Reader。自己的包里可以按同样风格:http.NewClient 而非 http.NewHTTPClient。

嵌入:Go 的组合方式#

Go 没有继承,只有嵌入(embedding)。把一个类型匿名地放进另一个类型,它的方法会被「提升」到外层:

go
type Base struct {
	ID   int64
	When time.Time
}

func (b Base) Describe() string {
	return fmt.Sprintf("base#%d", b.ID)
}

type Order struct {
	Base
	Amount int
}

o := Order{Base: Base{ID: 1}, Amount: 100}
o.Describe()   // base#1,方法被提升
o.ID           // 1,字段被提升

提升带来的「意外」#

go
type Order struct {
	Base
	Amount int
}

func (o Order) String() string {
	return "order"
}

如果 Base 和 Order 都定义了 String(),那么 o.String() 直接报歧义错误——必须显式指定:

go
o.Order.String()
o.Base.String()

嵌入指针的 nil 陷阱#

go
type Order struct {
	*Base
}

var o Order
o.Describe() // panic: nil pointer dereference

嵌入的是 nil 指针时,调用提升上来的方法会解引用 nil。要避免:

go
func (o Order) Describe() string {
	if o.Base == nil {
		return "空订单"
	}
	return o.Base.Describe()
}

接口嵌入#

go
type Reader interface {
	Read(p []byte) (n int, err error)
}

type ReadWriter interface {
	Reader
	Writer
}

接口嵌入是最常用的组合手段。

方法集:值类型和指针的区别#

这是接口实现里最容易懵的地方。

go
type Speaker interface {
	Speak()
}

type Dog struct{}

func (d Dog) Speak() {} // 值接收者

type Cat struct{}

func (c *Cat) Speak() {} // 指针接收者
赋值是否满足接口
var s Speaker = Dog{}✅ 值类型的方法集包含值接收者方法
var s Speaker = &Dog{}✅
var s Speaker = Cat{}❌ 值类型的方法集不含指针接收者方法
var s Speaker = &Cat{}✅

规律:T 的方法集只包含接收者为 T 的方法;\*T 的方法集包含接收者为 T 和 \*T 的全部方法。

所以:只要一个类型有指针接收者方法,就只应该用指针来满足接口。否则会出现「接口非 nil 但内部指针为 nil」的诡异错误。

常见陷阱#

结构体比较#

结构体可以用 == 比较,但要求所有字段可比较:

go
type Point struct{ X, Y int }
type Circle struct {
	Point
	Tags []string // 切片,不可比较
}

c1 := Circle{Tags: []string{"a"}}
c2 := Circle{Tags: []string{"a"}}
// c1 == c2  // 编译错误:struct containing []string cannot be compared

结构体包含互斥锁#

go
type Cache struct {
	mu    sync.Mutex
	items map[string]int
}

Cache 的值不能被复制。传参时用 *Cache。

匿名字段冲突#

go
type A struct{ Name string }
type B struct{ Name string }
type C struct {
	A
	B
}

c := C{}
// c.Name  // 歧义错误
c.A.Name = "x" // 明确指定

小结#

  • 所有方法统一使用指针接收者,除非类型是不可变的小值类型
  • 用嵌入做组合,注意方法提升的歧义和 nil 指针风险
  • 构造器返回指针 + error,在构造时完成校验
  • 值类型的方法集不含指针接收者方法——这是接口实现最容易踩的坑