Git Product home page Git Product logo

box's Introduction

boxCtx

使用过多的context.WithValue会导致context 层数过多,从而导致内存占用过多和降低效率,采用此工具可以有效的降低context的层级

用法

保持和标准库风格一致,box也采用WithValue方法加入元素

bCtx:=box.WithWalue(context.Background(), "a", "a")

boxCtx 也是 context.Context 所以context中的其他方法也适用,例如:

xCtx := context.WithValue(bCtx,"x","x")

或者

c, f := context.WithCancel(bCtx)

注意 box.WithValue 方法定义为:在已经存在的boxCtx中增加key,value,如果boxCtx不存在,则创建

func WithValue(parent context.Context, key, val any) context.Context {
	if box, ok := From[*boxCtx](parent, self); ok {
		box.put(key, val)
		return parent
	}

	b := new(parent)
	b.put(key, val)
	return b
}

可以使用context.Value直接获取,box 也提供了一个范型的From方法,用于方便获取

x , ok := box.From[string](bCtx, "x")

box.From方法兼容context.Value

最佳实践

尽量将boxCtx放置在context树的最上层

box's People

Contributors

it512 avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.