options

package
v1.7.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 15, 2024 License: MIT Imports: 1 Imported by: 2

README

options

Realization of pattern functional parameter.

Example:

package a

type A struct{
    foo string
    bar string
}

func New(opts ...Option[A]) (*A, error){
    a := A{
        foo: "defaultFoo",
        bar: "defaultBar",
    }
    if err := ApplyOptions(&a, opts...); err != nil{
        return nil, fmt.Errorf("applying opts: %w", err)
    }
    return &a, nil
}

func WithFoo(v string) Option[A]{
    return func(target *A) error{
        target.foo = v
    }
}

func WithBar(v string) Option[A]{
    return func(target *A) error{
        if v == ""{
            return errors.New("bar can bot be empty")
        }
        target.bar = v
    }
}
package main

func main(){
    a1, err := a.New()
    fatalOnErr(err)
    a2, err := a.New(a.WithFoo("customFoo"))
    fatalOnErr(err)
    a3, err := a.New(a.WithFoo(""), a.WithBar("")) // returns non-nil err

    for idx, el := range []*A{a1, a2, a3}{
        fmt.Printf("%d: %+v\n", idx, el)
    }
}

func fatalOnErr(err error){
    if err != nil{
        log.Fatal(err)
    }
}

func FatalOnNil(err error){
    if err == nil{
        log.Fatal(err)
    }
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ApplyOptions

func ApplyOptions[T any](target *T, opts ...Option[T]) error

Apply given opts. Any of aopts must not be nil. In case of error on any position, opts execution will be stopped.

Types

type Option

type Option[T any] func(target *T) error

Realization of functional option pattern

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL