英文:
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 <name> <anothertype>
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("Value of key is %d", k)
}
which can be used as
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论