Skip to content
This repository has been archived by the owner on May 21, 2022. It is now read-only.

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

Open
stonedu1011 opened this issue Jan 20, 2021 · 0 comments

Comments

@stonedu1011
Copy link

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.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant