Home

opt @main - refs - log -
-
https://git.jolheiser.com/opt.git
Functional options
-rw-r--r--
6 B
.gitignore
-rw-r--r--
1.1 kB
LICENSE
-rw-r--r--
636 B
README.md
-rw-r--r--
75 B
go.mod
-rw-r--r--
161 B
go.sum
-rw-r--r--
523 B
opt.go
-rw-r--r--
416 B
opt_example_test.go
-rw-r--r--
1.4 kB
opt_test.go

opt

opt is a tiny package that reduces boilerplate for functional options.

Simply decide whether your options can return errors or not, then use the corresponding type.

Without errors:

type Foo struct {
	Bar string
}

func WithBar(b string) opt.Func[Foo] {
	return func(f *Foo) {
			f.Bar = b
    }
}

With errors:

type Foo struct {
	Bar string
}

func WithBar(b string) opt.ErrorFunc[Foo] {
	return func(f *Foo) error  {
			f.Bar = b
			return nil
		}
}

License

MIT

Credit to @segfaultax in the Discord Gophers server for the idea and starting implementation.