Skip to content

Guideline: For functional options, don't recommend closures #74

@abhinav

Description

@abhinav

Our recommendation right now includes this pattern,

type Option interface{ apply(*options) }

type optionFunc func(*options)

And then all options are implemented using optionFunc and closures.

func WithTimeout(d time.Duration) Option {
  return optionFunc(func(o *options) {
    o.Timeout = d
  })
}

This is not the pattern we should be encouraging because it makes Options
too opaque. We cannot print them or compare them, or introspect values inside
them.

We should instead recommend declaring a new type for each option.

type timeoutOption time.Duration

func WithTimeout(t time.Duration) Option {
  return timeoutOption(t)
}

func (o timeoutOption) apply(opts *options) {
  opts.Timeout = time.Duration(o)
}

// And

type loggerOption struct{ L *zap.Logger }

func WithLogger(l *zap.Logger) Option {
  return loggerOption{L: l}
}

func (o *loggerOption) apply(opts *options) {
  o.Logger = o.L
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions