Golang:不应该复制包中定义的类型的值。

huangapple go评论84阅读模式
英文:

Golang: Values containing the types defined in this package should not be copied

问题

链接https://golang.org/pkg/sync/中指出:“不应复制包中定义的类型的值。”

为什么会这样?如果我忽略这个建议会发生什么?

英文:

The link https://golang.org/pkg/sync/ states "Values containing the types defined in this package should not be copied."

Why is it so? What would happen if I ignore the advice ?

答案1

得分: 4

这将不再起作为同步原语的作用。最好的情况是你会得到不可预测的行为。
想象一下锁(例如)就像是一个旗帜。如果锁定了,旗帜就被设置了。如果你复制这个锁(复制旗帜的状态),复制品会表现得好像它被锁定了,而实际上并没有。如果你解锁复制品,原始的锁并不会改变,所以它会表现得好像它被锁定了,而实际上它不应该再被锁定了。

英文:

It would simply not work as a synchronization primitive anymore. At best you would get unpredictable behavior.
Think of a lock (for instance) as a flag. If it is locked, the flag is set. If you copy that lock (you copy the flag's state), the copy would behave as if it was locked while it’s not. If you unlock the copy, the original won’t change so it will behave as if it was locked while it’s not supposed to be locked anymore.

huangapple
  • 本文由 发表于 2016年12月19日 18:32:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/41220596.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定