Skip to content

amirylm/go-options

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

8 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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.

About

Options pattern in Golang

Resources

License

Stars

Watchers

Forks

Packages

No packages published