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) Context

Parameters & Attributes

NameTypeDescription
parentContextNon-nil parent context.
keyanyComparable map key, or a package-specific comparable context key.
valanyValue 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{}))}
Go Reference