0%

Golang中阻止拷贝NoCopy

  在现实的项目开发过程中,都有 Nocpoy 对象的需求,那么如何在golang中实现这个特性呢?Go中没有原生的禁止拷贝的方式,所以如果有的结构体,你希望使用者无法拷贝,只能指针传递保证全局唯一的话,可以这么干,定义 一个结构体叫 noCopy,要实现 sync.Locker 这个接口

1
2
3
4
type noCopy struct{}

func (*noCopy) Lock() {}
func (*noCopy) Unlock() {}

然后把 noCopy 嵌到你自定义的结构体里,然后 go vet 就可以帮我们进行检查了

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package main

import "fmt"

type noCopy struct{}

func (*noCopy) Lock() {}
func (*noCopy) Unlock() {}

type Demo struct {
noCopy noCopy
}

func main() {
d := Demo{}
fmt.Printf("d: %+v\n", d)

e := d
fmt.Printf("e: %+v\n", e)
}

运行go代码静态检查, go vet main.go

遗憾的是golang至1.13版本仍然没有添加语法层面的nocopy实现,上面例子仍然可以运行