Skip to content

v4 preview 1, "functional options" for constructors don't work as intended outside the package #59

@lggomez

Description

@lggomez

Migrated from dgrijalva/jwt-go#447

stonedu1011 commented on Jan 20

I understand it's at very early stage, so just want to provide some feedback after my attempt to use it.

We uses similar API designed inspired by (this article)[https://dave.cheney.net/2014/10/17/functional-options-for-friendly-apis] in our team. This approach only works if the functional options takes exported type with exported fields. Otherwise, the constructor is completely not configurable.

Here is the patterns we ends up using, in case we want to keep the Type's field hidden:

type Options func(*Opt)

type Opt struct {
    ConfigurableField1 type
    ConfigurableField2 type
}

type SomeType struct {
    field1 type
    field2 type
}

func New(opts ...Options) *SomeType {
    opt := Opt{
        // defaults
    }
    for _, optFunc := range opts {
        optFunc(&opt)
    }
    return &SomeType {
        field1: opt.ConfigurableField1,
        field2: opt.ConfigurableField2,
    }
}

This is a great library and I hope the V4 reaches a stable state soon.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions