Not Encourage Copy Hint In Go Language¶
In cpp, some classes cannot be copied as their copy constructers are disable. For example, you can never pass an iostream
by value, only reference is allowed.
Based on provious blogs, we know that if we pass by pointer or interface, the value will be passed like reference.
Define and Use Error Properly in Go
Go has no way to disable the copy, but it provides a way to check whether the code not wishes to copy something.
Briefly, just define and emit it in struct helps vet
check. Additional, add a mutex
in struct also helps to check by cmd/vet
for not copy.
type noCopy struct{}
// Lock is a no-op used by -copylocks checker from `go vet`.
func (*noCopy) Lock() {}
func (*noCopy) Unlock() {}
Could check the idea from rsc, also that issue discussed how to document a type should not be copied.
Page here introduces usages in go standard library, could check for briefing.
What does "nocopy after first use" mean in golang and how
Why mutex is not designed as an interface to forcely forbid copy?¶
Created a concersation in group, could check this issue.
Based on the question, I received two persuasive answers:
- copy mutex still share the same one has nearly no scenario, as we use mutex to protest something.
- the zero value of sync.Mutex would not be usable
Conclusion¶
Go doesn’t provide feature to disable copy, it only provides cmd/vet
to analyze whether there is a wrong copy operation.