Gopher 需要知道的几个结构体骚操作

开发 后端
我们知道 Go 没有继承的概念,接口结构体多使用组合,很多开源产品或是源代码都有大量的内嵌 (embeded field) 字段,用于特殊目的。

[[440247]]

本文转载自微信公众号「董泽润的技术笔记」,作者董泽润。转载本文请联系董泽润的技术笔记公众号。

我们知道 Go 没有继承的概念,接口结构体多使用组合,很多开源产品或是源代码都有大量的内嵌 (embeded field) 字段,用于特殊目的

NoCopy

  1. package main 
  2.  
  3. import ( 
  4.  "sync" 
  5.  
  6. func test(wg sync.WaitGroup) { 
  7.  defer wg.Done() 
  8.  wg.Add(1) 
  9.  
  10. func main() { 
  11.  var wg sync.WaitGroup 
  12.  wg.Add(1) 
  13.  go test(wg) 
  14.  wg.Wait() 

这是非常经典的 case, 程序执行报错 all goroutines are asleep - deadlock!, 解决也很简单,把 wg 由值传递变成指针类型即可。本质是 WaitGroup 内部维护了计数,不允许 copy 变量,还有 sync.Mutex 锁也是不允许 copy 的

解决办法很简单,需要 CI 时由 linter 检测出来,最好运行时也能有检测机制,这方面的讨论请参考issue 8005[1]

  1. zerun.dong$ go vet aaa.go 
  2. # command-line-arguments 
  3. ./aaa.go:7:14: test passes lock by value: sync.WaitGroup contains sync.noCopy 
  4. ./aaa.go:15:10: call of test copies lock value: sync.WaitGroup contains sync.noCopy 

这是 go vet 结果,报错己经很明显了

  1. type noCopy struct{} 

noCopy 定义非常简单,空结构体,zero size 不占用空间(前提是非结构体的最后一个字段,否则还要是有 8 byte 空间开销)

sync.WaitGroup[2] 内嵌 noCopy 字段,防止 Cond 变量被复制

  1. type WaitGroup struct { 
  2.  noCopy noCopy 
  3.  
  4.  // 64-bit value: high 32 bits are counter, low 32 bits are waiter count
  5.  // 64-bit atomic operations require 64-bit alignment, but 32-bit 
  6.  // compilers only guarantee that 64-bit fields are 32-bit aligned. 
  7.  // For this reason on 32 bit architectures we need to check in state() 
  8.  // if state1 is aligned or notand dynamically "swap" the field order if 
  9.  // needed. 
  10.  state1 uint64 
  11.  state2 uint32 

上面是 sync.WaitGroup 结构体的定义,同时注意 noCopy 是源码中不可导出的定义。如果用户代码也想实现 NoCopy 呢?可以参考 grpc DoNotCopy[3]

  1. // DoNotCopy can be embedded in a struct to help prevent shallow copies. 
  2. // This does not rely on a Go language feature, but rather a special case 
  3. // within the vet checker. 
  4. type DoNotCopy [0]sync.Mutex 

非常简单,Mutex 零长数组,不占用空间。由于 vet checker 会检测 Mutex,相当于替我们实现了 noCopy 功能

DoNotCompare

Golang Sepc Comparison_operators[4] 官方文档描述常见类型比较运算( == != > < <= >=)的结果,详细内容看官方文档 https://go.dev/ref/spec#Comparison_operators

  • In any comparison, the first operand must be assignable to the type of the second operand, or vice versa.
  • The equality operators == and != apply to operands that are comparable. The ordering operators <, <=, >, and >= apply to operands that are ordered.
  • Struct values are comparable if all their fields are comparable. Two struct values are equal if their corresponding non-blank fields are equal.
  • Slice, map, and function values are not comparable. However, as a special case, a slice, map, or function value may be compared to the predeclared identifier nil. Comparison of pointer, channel, and interface values to nil is also allowed and follows from the general rules above.

对于 struct 来讲,只有所有字段全部 comparable 的(不限大小写是否导出),那么结构体才可以比较。同时只比较 non-blank 的字段,举个例子:

  1. type T struct { 
  2.     name string 
  3.     age int 
  4.     _ float64 
  5. func main() { 
  6.    x := [...]float64{1.1, 2, 3.14} 
  7.    fmt.Println(x == [...]float64{1.1, 2, 3.14}) // true 
  8.    y := [1]T{{"foo", 1, 0}} 
  9.    fmt.Println(y == [1]T{{"foo", 1, 1}}) // true 

运行后,结果均为 true

Slice, Map, Function 均是不可比较的,只与判断是否为 nil. 所以我们可以利用这两个特性,内嵌函数来实现不可比较,参考 protobuf DoNotCompare[5]

  1. // DoNotCompare can be embedded in a struct to prevent comparability. 
  2. type DoNotCompare [0]func() 

如果比较会报错

  1. type DoNotCompare [0]func() 
  2.  
  3. type T struct { 
  4.     name string 
  5.     age int 
  6.     DoNotCompare 
  7. func main() { 
  8. // ./cmp.go:13:21: invalid operation: T{} == T{} (struct containing DoNotCompare cannot be compared) 
  9.     fmt.Println(T{} == T{}) 

NoUnkeyedLiterals

结构体初始化有两种:指定字段名称,或者按顺序列出所有字段,不指定名称

  1. type User struct{ 
  2.     Age int 
  3.     Address string 
  4.  
  5. u := &User{21, "beijing"

这样写的问题非常大,如果新增字段会不兼容

  1. type User struct{ 
  2.     Age int 
  3.     Address string 
  4.     Money int 
  5.  
  6. func main(){ 
  7. // ./struct.go:11:15: too few values in User{...} 
  8.   _ = &User{21, "beijing"

上面的例子,能在编译期报错还是可接受的,如果同类型的调换顺序,那才叫坑爹... 所以这时需要 NoUnkeyedLiterals[6]

  1. // NoUnkeyedLiterals can be embedded in a struct to prevent unkeyed literals. 
  2. type NoUnkeyedLiterals struct{} 

很简单,就是一个空结构体,这是 Protobuf 的实现。很多时候我们都用空的结构体占位符实现

  1. type User struct{ 
  2.     _ struct{} 
  3.     Age int 
  4.     Address string 
  5.  
  6. func main(){ 
  7. // ./struct.go:10:11: cannot use 21 (type intas type struct {} in field value 
  8. // ./struct.go:10:15: cannot use "beijing" (type untyped string) as type int in field value 
  9. // ./struct.go:10:15: too few values in User{...} 
  10. _ = &User{21, "beijing"

报错很明显了,字段类型不匹配,有人会说初始化写上 struct{} 不就可以了?

  1. _ = &User{struct{}{}, 21, "beijing"

这样确实可以工作,但是占位符 _ 的字段是不可导出的,所以 import 其它包的 NoUnkeyedLiterals 结构体同样会报错

Copier 库

最后推荐一个非常实用的 copier[7] 库,CRUD Boy 经常结构体转来转去的,比如 dto, dao 互转,或是 dao 与其它互转,如果修改了 dao 结构体,还要记得修改其它转换逻辑,非常繁琐

  1. package main 
  2. import ( 
  3.   "fmt" 
  4.   "github.com/jinzhu/copier" 
  5.  
  6. type User struct { 
  7.   Name string 
  8.   Age  int 
  9.  
  10. type Employee struct { 
  11.   Name string 
  12.   Age  int 
  13.   Role string 
  14.  
  15. func main() { 
  16.   user := User{Name"dj", Age: 18} 
  17.   employee := Employee{Role: "admin"
  18.  
  19.   copier.Copy(&employee, &user
  20.   // main.Employee{Name:"dj", Age:18, Role:"admin"
  21.   fmt.Printf("%#v\n", employee) 

打印 Employee 发现 name, age 字段己经赋值了,非常好用。感兴趣的可以查看官网,支持非常多的高级玩法

注意:这里是隐式的,有人偏好所有字段显示赋值,大家怎么看?

 

责任编辑:武晓燕 来源: 董泽润的技术笔记
相关推荐

2019-12-11 09:23:51

JavaScriptHTMLXML

2017-04-13 10:08:30

软件开发开发

2011-09-20 10:56:35

云计算PaaS

2022-04-29 09:00:00

Platform架构内核线程

2018-09-10 09:26:33

2022-08-10 09:03:35

TypeScript前端

2023-01-20 11:51:40

性能测试系统

2017-11-14 13:48:26

数据结构学习

2009-06-30 13:00:30

JSP入门

2018-05-30 15:15:47

混合云公共云私有云

2023-08-16 15:57:53

2020-03-03 14:35:34

LinuxRedis命令

2019-10-23 10:36:46

DevSecOpsDevOps

2023-01-30 11:43:04

开源代码

2020-03-27 12:30:39

python开发代码

2016-09-08 14:40:44

2021-01-11 18:33:07

云原生

2014-07-31 17:13:50

编码程序员

2020-11-23 11:30:00

IDEA技巧开发

2023-12-21 14:43:30

Python字典
点赞
收藏

51CTO技术栈公众号