`atomic.Pointer[T]`和`atomic.Value`在什么情况下使用?

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

when to use atomic.Pointer[T] versus atomic.Value

问题

go1.19引入了atomic.Pointer,我注意到一些源代码已经从atomic.Value转移到了atomic.Pointer。(例如:426074: sync: switch Map to use atomic.Pointer422174: encoding/gob: change typeInfo.encoder type to atomic.Pointer[T]

所以我的问题是:

  1. 如果我的代码考虑使用泛型,是否可以将所有的atomic.Value转换为atomic.Pointer,在什么情况下应该更多地使用atomic.Value
  2. atomic.Value的存在只是为了兼容性的原因吗?是否应该逐渐废弃atomic.Value
英文:

go1.19 introduce atomic.Pointer, and I noticed Some source code has moved from atomic.Value to atomic.Pointer. (ex: 426074: sync: switch Map to use atomic.Pointer, 422174: encoding/gob: change typeInfo.encoder type to atomic.Pointer[T])

So my question are:

  1. If my code considers using generics, can all atomic.Value's be converted to atomic.Pointer's and what are the cases where atomic.Value's should be used more?
  2. Is the existence of atomic.Value only for compatibility reasons, should atomic.Value be gradually deprecated?

答案1

得分: 2

更喜欢使用更具体的原子类型而不是atomic.Value。就像在处理bool值时更喜欢使用atomic.Bool而不是atomic.Value一样,在处理指针时更喜欢使用atomic.Pointer而不是atomic.Value

> 如果我的代码考虑使用泛型,是否可以将所有的atomic.Value转换为atomic.Pointer?在哪些情况下应该更多地使用atomic.Value

当值是指针时,可以将atomic.Value转换为atomic.Pointer

> atomic.Value的存在只是为了兼容性的原因吗?是否应该逐渐弃用atomic.Value

atomic.Value更具体的原子类型并不能涵盖所有可能的类型。因此仍然需要atomic.Value

英文:

Prefer more specific atomic types over atomic.Value. Just as atomic.Bool is preferred over atomic.Value when working with bool values, atomic.Pointer is preferred over atomic.Value when working with pointers.

> If my code considers using generics, can all atomic.Value's be converted to atomic.Pointer's and what are the cases where atomic.Value's should be used more?

Convert from atomic.Value to atomic.Pointer when the value is a pointer.

> Is the existence of atomic.Value only for compatibility reasons, should atomic.Value be gradually deprecated?

The atomic types that are more specific than atomic.Value do not cover all possible types. There's still a need atomic.Value.

huangapple
  • 本文由 发表于 2022年9月7日 10:47:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/73629542.html
匿名

发表评论

匿名网友

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

确定