Uber Go语言编码规范( 七 )

测试表使向错误消息添加上下文 , 减少重复的逻辑以及添加新的测试用例变得更加容易 。
我们遵循这样的约定:将结构体切片称为tests 。每个测试用例称为tt 。此外 , 我们鼓励使用give和want前缀说明每个测试用例的输入和输出值 。
tests := []struct{ give string wantHost string wantPort string}{ // ...}for _, tt := range tests { // ...}功能选项
功能选项是一种模式 , 您可以在其中声明一个不透明Option类型 , 该类型在某些内部结构中记录信息 。您接受这些选项的可变编号 , 并根据内部结构上的选项记录的全部信息采取行动 。
将此模式用于您需要扩展的构造函数和其他公共API中的可选参数 , 尤其是在这些功能上已经具有三个或更多参数的情况下 。
Bad
// package dbfunc Connect( addr string, timeout time.Duration, caching bool,) (*Connection, error) { // ...}// Timeout and caching must always be provided,// even if the user wants to use the default.db.Connect(addr, db.DefaultTimeout, db.DefaultCaching)db.Connect(addr, newTimeout, db.DefaultCaching)db.Connect(addr, db.DefaultTimeout, false /* caching */)db.Connect(addr, newTimeout, false /* caching */)vs.
Good
type options struct { timeout time.Duration caching bool}// Option overrides behavior of Connect.type Option interface { apply(*options)}type optionFunc func(*options)func (f optionFunc) apply(o *options) { f(o)}func WithTimeout(t time.Duration) Option { return optionFunc(func(o *options) { o.timeout = t })}func WithCaching(cache bool) Option { return optionFunc(func(o *options) { o.caching = cache })}// Connect creates a connection.func Connect( addr string, opts ...Option,) (*Connection, error) { options := options{ timeout: defaultTimeout, caching: defaultCaching, } for _, o := range opts { o.apply(&options) } // ...}// Options must be provided only if needed.db.Connect(addr)db.Connect(addr, db.WithTimeout(newTimeout))db.Connect(addr, db.WithCaching(false))db.Connect( addr, db.WithCaching(false), db.WithTimeout(newTimeout),)还可以参考下面资料:

  • Self-referential functions and the design of options
  • Functional options for friendly APIs
推荐阅读
  • Go GC 卡顿由秒级降到毫秒级以下:到底做了哪些优化?
原文链接:https://tonybai.com/2019/10/12/uber-go-style-guide/  , 如果打不开 , 可以访问:https://studygolang.com/articles/23941
译者:白明 (tonybai)
喜欢本文的朋友 , 欢迎关注“Go语言中文网”




推荐阅读