Home > Article > Backend Development > How to Efficiently Pass Multiple Key-Value Pairs with context.WithValue()?
context.WithValue: Adding Multiple Key-Value Pairs
The context package in Go allows developers to pass request-specific data to request handling functions using the context.WithValue() function. This function creates a new context, which is a copy of the parent context, with the provided key-value pair.
Multiple Key-Value Pairs in Context
When working with multiple key-value pairs, you have several options:
type Values struct { m map[string]string } func (v Values) Get(key string) string { return v.m[key] }
Using this struct, you can add it to the context as follows:
v := Values{map[string]string{ "1": "one", "2": "two", }} c := context.WithValue(c, "myvalues", v) fmt.Println(c.Value("myvalues").(Values).Get("2")) // Prints "two"
Performance Considerations
The best approach depends on the specific use case:
Remember that context.Context is immutable, so each time you add a new key-value pair, a new context is created. Consider the number of key-value pairs and the performance requirements when choosing an approach.
The above is the detailed content of How to Efficiently Pass Multiple Key-Value Pairs with context.WithValue()?. For more information, please follow other related articles on the PHP Chinese website!