options

package module
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Jul 9, 2023 License: MIT Imports: 0 Imported by: 7

README

Golang Options

API Reference License Go version Github Actions Github Actions

Overview

This repository contains just a few lines of code, created for reusing cross multiple projects but you can easily implment these lines in your own code.

Options pattern allows decoupling and encapsulation of object creation.

Golang's variadic functions are used to accept multiple functions or none. For example, if we want to create a new object:

o := New(WithSize(32), WithID("0x111"))

Using this approach, we can easily change the internal structure of our options, while preserving a stable interface.

Usage

go get github.com/amirylm/go-options

import (
    "github.com/amirylm/go-options"
)

func main() {
    hello := New(WithSize(4), WithName("hello"))

    world := New(WithName("world"))

    fmt.Println(hello.name) // hello
	fmt.Println(world.name) // world 
	fmt.Println(world.size) // 0 
}

type myStruct struct {
	size int
	name string
}

func WithSize(size int) options.Option[myStruct] {
	return func(o *myStruct) {
		o.size = size
	}
}

func WithName(name string) options.Option[myStruct] {
	return func(o *myStruct) {
		o.name = name
	}
}

func New(o ...options.Option[myStruct]) *myStruct  {
	return options.Apply(nil, o...)
}

Contributing

Contributions to this repository are welcomed and encouraged! If you find a bug or have an idea for an improvement, please open an issue or submit a pull request.

License

go-options is an open-source software licensed under the MIT License. Feel free to use, modify, and distribute this library as permitted by the license.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Apply

func Apply[O any](opts *O, options ...Option[O]) *O

Apply calls the given opt functions with generic options struct.

func New(o ...options.Option[MyOptions]) {
	opts := options.Apply(nil, o...)
 	...
}

Types

type Option

type Option[O any] func(*O)

Options is a generic function that represents some option, e.g.

func WithSize(size int) options.Option[MyOptions] {
	return func(opts *MyOptions) {
		opts.size = size
	}
}

Jump to

Keyboard shortcuts

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