如何在Go中定义上下文的键(key)

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

How to define the key of context in go

问题

为什么一般定义是

type key int
type userKey key

而不是

type userKey int

使用第一种方式有什么好处?

我看到官方文档中没有解释
然后我看到每个人都在使用第一种方式

英文:

Why is the general definition of

type key int
type userKey key

instead of

type userKey int

What are the benefits of using the first one?

I see that there is no explanation in the official documentation
Then I see that everyone is using the first

答案1

得分: 2

type <name> <anothertype> 创建一个类型,其内存布局与 anothertype 相同,但没有其方法。

这样可以在一个本来不可能的类型上声明方法。

例如,使用 type key int 可以在 key 上实现 fmt.Stringer

type key int

func (k key) String() string {
	return fmt.Sprintf("Value of key is %d", k)
}

可以这样使用:

func (k key) String() string {
	return fmt.Sprintf("Value of key is %d", k)
}

func main() {
	var k key = 20
	fmt.Printf("k: %v\n", k) // k: Value of key is 20

	var intK int = 10
	fmt.Printf("intK: %v\n", intK) //intK: 10
}
英文:

type &lt;name&gt; &lt;anothertype&gt; creates a type whose memory layout is same as anothertype but does not have its methods.

This allows to declare methods on a type that otherwise would not be possible.

e.g. with type key int it is possible to implement fmt.Stringer with key,

type key int

func (k key) String() string {
	return fmt.Sprintf(&quot;Value of key is %d&quot;, k)
}

which can be used as


func (k key) String() string {
	return fmt.Sprintf(&quot;Value of key is %d&quot;, k)
}

func main() {
	var k key = 20
	fmt.Printf(&quot;k: %v\n&quot;, k) // k: Value of key is 20

	var intK int = 10
	fmt.Printf(&quot;intK: %v\n&quot;, intK) //intK: 10
}

huangapple
  • 本文由 发表于 2023年7月8日 16:41:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/76642089.html
匿名

发表评论

匿名网友

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

确定