package main import ( "context" "fmt" "sync" ) type MyContext struct { ctx context.Context m sync.Map } func (m * MyContext) WithValue(parent MyContext, key, val interface{}) MyContext { //ctx := m.WithValue(parent,key,val) ctx := new(MyContext) ctx.ctx =context.WithValue(parent.ctx,key,val) m.m.Store(key,val) ctx.m = m.m return *ctx } func (m * MyContext) Value( key interface{}) interface{}{ val ,_ :=m.m.Load(key) return val } func NewMyContext() MyContext{ mc := MyContext{ ctx : context.Background(), } return mc } func main() { mc := NewMyContext() ctx :=mc.WithValue(mc,"key1","value1") ctx1 :=mc.WithValue(ctx,"key2","value2") fmt.Println(ctx.Value("key2"),ctx1.Value("key2")) }