once

package module
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Apr 7, 2025 License: MIT Imports: 2 Imported by: 2

README

once - a nicer API for doing things once

GoDoc unit tests report card codecov

Install:

go get github.com/singlestore-labs/once

Once is a small package that provides a nicer (as compared to sync.Once) API for doing things once.

Documentation

Overview

Package once exists because sync.Once is annoying to use because each place you use it must provide the function to execute. That's great if you want to do different things, but if you always want to do the same thing, it's repetitive.

Further, ReliableError provides a way to use Once to make go-routines that return error easy to write safely.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Error

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

func ReliableError

func ReliableError(c chan error, e *error) *Error

ReliableError provides a way to guarantee that a go routine returns an error over a channel, even if there is a panic. This is important because a common idiom is to wait for a go-routine to finish by reading a error from a channel.

Without something like ReliableError, that is unsafe.

The other idiom, to use a sync.WaitGroup and then defer wg.Done() doesn't provide a reliable way to return an error. If you're setting an error value, that error may not be set if the go-routine panics.

Example:

  echan := make(chan error)

  go func() {
	var err error
	re := ReliableError(echan, &err)
	defer re.Catch()

	... do stuff
	err = something()
	if err != nil {
	   re.Do()
	   return
	}
	... repeat as needed
  }()

  err :- <-echan

func (*Error) Catch

func (e *Error) Catch()

Catch should be deferred right after calling ReliableError

func (*Error) Do

func (e *Error) Do()

Do is optional but is useful to when returning from the function that is generating an error.

type Once

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

func New

func New(f func()) *Once

New provides the function that Do will will call. The function will only be called once no matter how many times Do is invoked.

func (*Once) Do

func (o *Once) Do()

Call the function provided in New. Calling Do on an uninitialized Once object will panic.

Jump to

Keyboard shortcuts

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