context

package
v0.0.0-...-3bb151c Latest Latest
Warning

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

Go to latest
Published: May 8, 2026 License: MIT Imports: 3 Imported by: 24

Documentation

Overview

Package context 提供类型化上下文槽位和更轻量的值注入辅助。

这个包聚焦于在 context.Context 中存取具名类型值,以及为同一类上下文值定义默认值与读取入口。

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func WithValue

func WithValue(parent context.Context, key any, val any) context.Context

WithValue 类似 context.WithValue,但跳过 key 的 comparable 检查。

它适合性能敏感且已自行保证 key 可安全比较的场景。

Types

type Context

type Context[T any] interface {
	// Inject 将 value 写入 ctx,并返回派生后的 context.Context。
	Inject(ctx context.Context, value T) context.Context
	// From 从 ctx 中读取值;若不存在且配置了默认值则返回默认值,否则 panic。
	From(ctx context.Context) T
	// MayFrom 从 ctx 中尝试读取值,并报告是否存在。
	MayFrom(ctx context.Context) (T, bool)
}

Context 表示一个可向 context.Context 注入和读取特定类型值的槽位。

func New

func New[T any](optFns ...OptionFunc[T]) Context[T]

New 创建一个类型化的上下文槽位。

Example
package main

import (
	stdcontext "context"
	"fmt"

	xcontext "github.com/octohelm/x/context"
)

func main() {
	slot := xcontext.New[string]()
	ctx := slot.Inject(stdcontext.Background(), "alice")

	fmt.Println(slot.From(ctx))
}
Output:
alice

type OptionFunc

type OptionFunc[T any] func(c *ctx[T])

OptionFunc 表示创建类型化 Context 时的配置项。

func WithDefaults

func WithDefaults[T any](v T) OptionFunc[T]

WithDefaults 为 Context[T] 配置固定默认值。

Example
package main

import (
	stdcontext "context"
	"fmt"

	xcontext "github.com/octohelm/x/context"
)

func main() {
	slot := xcontext.New(xcontext.WithDefaults("guest"))

	fmt.Println(slot.From(stdcontext.Background()))
}
Output:
guest

func WithDefaultsFunc

func WithDefaultsFunc[T any](defaultsFunc func() T) OptionFunc[T]

WithDefaultsFunc 为 Context[T] 配置延迟求值的默认值函数。

Jump to

Keyboard shortcuts

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