go nocopy 不可复制的实现
生活随笔
收集整理的這篇文章主要介紹了
go nocopy 不可复制的实现
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
在日常的項目開發過程中,都有?Nocpoy (不可復制)對象的需求,在golang怎么中實現這個特性呢?
在sync/cond.go中,有下面的實現。
// noCopy may be embedded into structs which must not be copied // after the first use. // // See https://golang.org/issues/8005#issuecomment-190753527 // for details. type noCopy struct{}// Lock is a no-op used by -copylocks checker from `go vet`. func (*noCopy) Lock() {}其實我們所使用的sync.WaitGroup內部就是包含了這樣的一個nocopy的結構體,來實現不可復制
// A WaitGroup must not be copied after first use. type WaitGroup struct {noCopy noCopy// 64-bit value: high 32 bits are counter, low 32 bits are waiter count.// 64-bit atomic operations require 64-bit alignment, but 32-bit// compilers do not ensure it. So we allocate 12 bytes and then use// the aligned 8 bytes in them as state.state1 [12]bytesema uint32 }注意:
1. 該noCopy并沒有導出來,我們不可使用
2. 想要實現NoCopy,需要自己定義一個這樣的結構體實現其Lock()接口即可,結構體名字隨意
3. 即使包含了NoCopy的結構體,也不是真正的就不可復制了,實際上毫無影響,無論是編譯,還是運行都毫不影響
4. 只有在go vet命令下,才會提示出其中的nocopy問題
5. vscode編譯器中可以直接提示出來
提示效果如下(fmt中,t1復制給t2中,都有綠色波浪線標示):
示例代碼的效果結果如下:
示例代碼如下:
package main import "fmt"// 需先定義noCopySign的結構體,該結構體名字隨意,關鍵是要定義下面的Lock()函數 type noCopySign struct{} func (*noCopySign) Lock() {}// 這里定義自己的結構體,包含上面的noCopySign結構體即可 type nocopyTest struct {nocopy noCopySigna int32 }func main() {/// 錯誤做法 ///t1 := nocopyTest{}t1.a = 111fmt.Printf("t1:%v \n", t1)t2 := t1t2.a = 222fmt.Printf("t1:%v,t2:%v \n", t1, t2)/// 正確做法 ///t3 := &nocopyTest{} // 一定要使用指針t3.a = 333fmt.Printf("t3:%v \n", t3)t4 := t3 // t4指向t3所指向的對象,所以是同一個對象t4.a = 444fmt.Printf("t3:%v,t4:%v \n", t3, t4) }?
總結
以上是生活随笔為你收集整理的go nocopy 不可复制的实现的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql 给列增加索引
- 下一篇: go 原子操作 atomic