分享:泛型+context 自动根据类型生成 ctx key

1次阅读

共计 398 个字符,预计需要花费 1 分钟才能阅读完成。

package gctx

import (
	"context"
	"fmt"
	"reflect"
)

type body[T any] struct {Value T}

type typeKey[T any] struct {
}

func Put[T any](ctx context.Context, value T) context.Context {key := typeKey[body[T]]{}
	return context.WithValue(ctx, key, body[T]{Value: value})
}

func Get[T any](ctx context.Context) (T, error) {key := typeKey[body[T]]{}
	value, ok := ctx.Value(key).(body[T])
	if !ok {
		var zero T
		return zero, errors.New("not found")
	}
	return value.Value, nil
}

正文完
 0