ctxv

package
v0.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 15, 2026 License: MIT Imports: 2 Imported by: 0

Documentation

Overview

Package ctxv provides type-safe context values through generic keys, eliminating the boilerplate of type assertions with context.Value. It has zero external dependencies.

Key[T] is a zero-value generic key type. NewKey creates a unique key bound to type T, and WithValue/Value/MustValue provide the standard context read-write operations with compile-time type safety.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Key

type Key[T any] struct {
	// contains filtered or unexported fields
}

Key is a typed context key that stores values of type T. Each call to NewKey produces a unique key, even for the same type parameter. The zero value is not usable; construct with NewKey.

func NewKey

func NewKey[T any](name string) *Key[T]

NewKey creates a new typed context key with the given name for debugging.

func (*Key[T]) MustValue

func (k *Key[T]) MustValue(ctx context.Context) T

MustValue retrieves a typed value from the context. Panics if the value is not found. This follows the Go Must convention (e.g. template.Must, regexp.MustCompile) where panic signals a programming error by the caller.

func (*Key[T]) String

func (k *Key[T]) String() string

String returns the key name for debugging.

func (*Key[T]) Value

func (k *Key[T]) Value(ctx context.Context) (T, bool)

Value retrieves a typed value from the context. Returns the value and true if found, the zero value and false otherwise.

func (*Key[T]) WithValue

func (k *Key[T]) WithValue(ctx context.Context, val T) context.Context

WithValue stores a typed value in the context and returns a derived context.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL