How to Pass Multiple Key-Value Pairs Efficiently with context.WithValue in Go?

Mary-Kate Olsen
Release: 2024-11-13 07:53:02
Original
253 people have browsed it

How to Pass Multiple Key-Value Pairs Efficiently with context.WithValue in Go?

Passing Multiple Key-Value Pairs to context.WithValue

Problem

Go's context package allows you to pass request-specific data using context.WithValue. However, it's not clear how to store multiple key-value pairs efficiently.

Solution

Consider the following options:

1. Multiple Calls to WithValue()

Call WithValue() multiple times, each time with a new key-value pair. This is straightforward but can be cumbersome.

2. Struct with Key-Value Pairs

Create a struct to hold all the key-value pairs and pass it as a single value to WithValue(). This allows easy access to all keys later, but can involve unnecessary copying of large data structures.

3. Hybrid Solution

Store key-value pairs in a map and create a wrapper struct that provides getters to access individual values. This allows safe concurrent access and avoids copying large amounts of data.

Implementation

Here's an example of the hybrid solution:

type Values struct {
    m map[string]string
}

func (v Values) Get(key string) string {
    return v.m[key]
}

func main() {
    v := Values{map[string]string{
        "1": "one",
        "2": "two",
    }}

    ctx := context.Background()
    ctx2 := context.WithValue(ctx, "myvalues", v)

    fmt.Println(ctx2.Value("myvalues").(Values).Get("2"))
}
Copy after login

Output:

two
Copy after login

Conclusion

The best approach depends on the specific requirements. For performance-critical scenarios with many key-value pairs, the hybrid solution is recommended. Otherwise, multiple calls to WithValue() or a struct with key-value pairs may be more convenient.

The above is the detailed content of How to Pass Multiple Key-Value Pairs Efficiently with context.WithValue in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template