Standard library / context
context.WithValue()
Attach request-scoped data, using a comparable package-specific key type to avoid collisions. Do not use context for optional parameters. Expected stdout: 'demo\n'.
Formal Syntax & Structure
go syntaxgo
func WithValue(parent Context, key, val any) ContextParameters & Attributes
| Name | Type | Description |
|---|---|---|
| parent | Context | Non-nil parent context. |
| key | any | Comparable map key, or a package-specific comparable context key. |
| val | any | Value to store; context values should be request-scoped. |
Return Value
Context
Derived Context containing the associated value.
Working Example
Example Snippetgo
package main
import ( "context" "fmt")
func main() { type key struct{} ctx := context.WithValue(context.Background(), key{}, "demo") fmt.Println(ctx.Value(key{}))}