#golang struct{} 一个作为key的用法
type keyType struct{} //空struct{}作为key,不占用内存空间
var xxxKey struct{} //同时避免了不同包使用ctx传值时出现冲突 var xxxKey2 keyType // 如果也是struct{} 。那么会覆盖。 type 宏定义之后,就好了
func main() {
ctx := context.WithValue(context.Background(), xxxKey, "A's value")
value := context.WithValue(ctx, xxxKey2, "nihao")
fmt.Println(value.Value(xxxKey))
fmt.Println(value.Value(xxxKey2))
}
type keyType struct{} //空struct{}作为key,不占用内存空间 type keyType2 struct{}
fmt.Printf("%p\n", &keyType{}) fmt.Printf("%p\n", &keyType{}) fmt.Printf("%p\n", &keyType2{}) // 这3地址是一样的
#评论
#评论 1 · 2023-02-23T08:48:08.030000Z
type 重命名。 认为是新的类型。 但这3是一样的, fmt.Printf("%p\n", &keyType{}) fmt.Printf("%p\n", &keyType{}) fmt.Printf("%p\n", &keyType2{})