Sobes.tech
Middle+

Kas saab struktuuri panna konteksti kaudu kasutades context.WithValue?

sobes.tech AI

Vastus AI-lt

Yes, in Go you can place a struct into the context using context.WithValue. However, it is important to remember that the context is intended for passing request-related data such as timeouts, deadlines, and metadata, not for passing large or mutable structures.

Example:

type User struct {
    ID   int
    Name string
}

ctx := context.Background()
user := &User{ID: 1, Name: "Alice"}
ctx = context.WithValue(ctx, "user", user)

// Retrieval
u, ok := ctx.Value("user").(*User)
if ok {
    fmt.Println(u.Name)
}

It is recommended to use key types that do not conflict with other packages, such as custom key types, to avoid collisions.