type Config struct {
host string
port int
timeout time.Duration
}
// 私有字段,使用工厂函数
func NewConfig(host string, port int) *Config {
return &Config{
host: host,
port: port,
timeout: 30 * time.Second, // 默认值
}
}
func (c *Config) WithTimeout(timeout time.Duration) *Config {
c.timeout = timeout
return c
}
4.2 结构体比较
go复制代码
type Point struct {
X, Y int
}
func main() {
p1 := Point{1, 2}
p2 := Point{1, 2}
p3 := Point{2, 3}
fmt.Println(p1 == p2) // true
fmt.Println(p1 == p3) // false
// 包含不可比较字段(如slice)的结构体不能比较
type BadStruct struct {
data []int
}
// b1 == b2 // 编译错误
}
4.3 空结构体
go复制代码
// 零内存占用,用作标记或map的键
type empty struct{}
var signal = struct{}{}
// 用作Set的键
type Set map[string]struct{}
func (s Set) Add(key string) {
s[key] = struct{}{}
}
func (s Set) Contains(key string) bool {
_, ok := s[key]
return ok
}
4.4 内存对齐与优化
go复制代码
// 不良的内存布局
type BadLayout struct {
b bool // 1字节
i int64 // 8字节
s string // 16字节
b2 bool // 1字节
} // 总大小:约32字节(包含填充)
// 优化的内存布局(按大小排序)
type GoodLayout struct {
s string // 16字节
i int64 // 8字节
b bool // 1字节
b2 bool // 1字节
} // 总大小:约24字节
func main() {
fmt.Println(unsafe.Sizeof(BadLayout{})) // 32
fmt.Println(unsafe.Sizeof(GoodLayout{})) // 24
}