栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

上下文接口设计

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

上下文接口设计

这是

context.Context
类型:

type Context interface {    Deadline() (deadline time.Time, ok bool)    Done() <-chan struct{}    Err() error    Value(key interface{}) interface{}}

这很简单。如果要编写它的实现,可以这样做吗?是的,很容易。由于没有“设置”方法,因此每个方法都只能返回默认值/
零值,并且是“有效”的实现。这正是背景和TODO上下文(

context.Background()
context.TODO()
)所做的。

如果您要添加从现有环境(例如,等) 派生
新上下文的功能作为接口本身的一部分,则将需要为所有人提供(有效)实现,这是不可行的;而且几乎不需要同时使用它们,因此这会浪费资源。

context.WithCancel()
context.WithDeadline()
Context

扩展负责添加实现。如果您查看

context
软件包的实现方式:
context/context.go
context.Context
则将看到不同的“派生”或“扩展”的不同实现:

// An emptyCtx is never canceled, has no values, and has no deadline. It is not// struct{}, since vars of this type must have distinct addresses.type emptyCtx int// A cancelCtx can be canceled. When canceled, it also cancels any children// that implement canceler.type cancelCtx struct {    Context    done chan struct{} // closed by the first cancel call.    mu       sync.Mutex    children map[canceler]bool // set to nil by the first cancel call    err      error  // set to non-nil by the first cancel call}// A timerCtx carries a timer and a deadline. It embeds a cancelCtx to// implement Done and Err. It implements cancel by stopping its timer then// delegating to cancelCtx.cancel.type timerCtx struct {    cancelCtx    timer *time.Timer // Under cancelCtx.mu.    deadline time.Time}// A valueCtx carries a key-value pair. It implements Value for that key and// delegates all other calls to the embedded Context.type valueCtx struct {    Context    key, val interface{}}

显然,我们可以弥补软件包

context.Context
中没有的其他有用扩展
context
。如果您有新想法,还可以将其添加到
Context
界面中吗?
这将破坏所有现有的实现 ,因为显然您的新想法未在其他人的当前实现中实现。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/484418.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号