singlet

package module
v0.3.1 Latest Latest
Warning

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

Go to latest
Published: May 1, 2023 License: Apache-2.0 Imports: 3 Imported by: 0

README

Singlet

Build Status codecov License Godoc

Singlet provides threadsafe, generic singletons for Golang.

Motivation

The common pattern of using sync.Once to implement a global singleton doesn't work well when the singleton value includes a generic type, since type arguments may not be available at a global level. Singlet provides a solution, allowing you to create threadsafe, generic singletons, anywhere in your code.

Example

To use singlet, first create a Singleton. Then call GetOrDo which will create and store a value in the Singleton, if one doesn't already exist, by calling the provided func, else it will return the existing value:

var s = &singlet.Singleton{}
cache1, _ := singlet.GetOrDo(s, cache.New[int]) 
cache2, _ := singlet.GetOrDo(s, cache.New[int]) // cache.New is only called once

if cache1 != cache2 {
    panic("caches should be equal")
}

You can also get a previously created value for a Singleton:

cache, _ := singlet.Get[*Cache[int]](singleton)
Type Mismatches

Calling Get or GetOrDo for a result type that doesn't match the previously stored result type for a Singleton will result in an ErrTypeMismatch:

singlet.GetOrDo(s, cache.New[int])
singlet.Get[string](s) // Returns ErrTypeMismatch

License

Copyright Jonathan Halterman. Released under the Apache 2.0 license.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrTypeMismatch = errors.New("the requested type does not match the singleton type")

Functions

func Get

func Get[T any](singleton *Singleton) (T, error)

Get returns a previously created value for the singleton, else the default value for T. Returns ErrTypeMismatch if the requested type does not match a type the existing singleton type. This function is threadsafe.

func GetOrDo

func GetOrDo[T any](singleton *Singleton, fn func() (T, error)) (result T, err error)

GetOrDo will create and store a value in the Singleton, if one doesn't already exist, by calling the fn, else it will return the existing value. If the fn returns an error, that error will be returned and no value will be stored in the singleton. If the requested type does not match a type the existing singleton type, ErrTypeMismatch is returned. This function is threadsafe.

Types

type Singleton

type Singleton struct {
	// contains filtered or unexported fields
}

Singleton can store a single value atomically when used with GetOrDo.

Jump to

Keyboard shortcuts

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