errfunc

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: May 22, 2022 License: MIT Imports: 0 Imported by: 0

README

errfunc

Go Reference

The errfunc package provides a generic implementation of the pattern described in the Errors are values Go blog post where a function becomes a no-op once an error has occured, allowing the user to simply call it repeatedly and then check for an error at the bottom.

For example, the original code from the blog post,

ew := &errWriter{w: fd}
ew.write(p0[a:b])
ew.write(p1[c:d])
ew.write(p2[e:f])
// and so on
if ew.err != nil {
  return ew.err
}

would become the following with this package:

ef := errfunc.New(fd.Write)
ef.Call(p0[a:b])
ef.Call(p1[c:d])
ef.Call(p2[e:f])
// and so on
if ef.Err() != nil {
  return ef.Err()
 }

Unlike the original implementation, this version can cleanly wrap any function that takes a single argument and returns a single value and an error. This means that it'll work well for io.Writers, io.Readers, and many other types.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Func

type Func[A, R any] struct {
	// contains filtered or unexported fields
}

Func is a function that takes a single argument of type A and returns a single result of type R along with an error. If an error is returned, it becomes a no-op.

func New

func New[A, R any](f func(A) (R, error)) *Func[A, R]

New returns a new Func that wraps f.

func (*Func[A, R]) Call

func (f *Func[A, R]) Call(a A) (r R)

Call calls the underlying function with the provided arguument and returns the result. If an error has occured on a previous call, it does not call the function and instead simply returns the zero-value of R.

func (*Func[A, R]) Err

func (f *Func[A, R]) Err() error

Err returns the error that was returned by the underlying function during a previous call of it, or nil if no such error occurred.

Jump to

Keyboard shortcuts

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