Wednesday, May 15, 2024
HomeGolangMigrate from Hashicorps go-multierror to plain library multierror (Golang 1.20)

Migrate from Hashicorps go-multierror to plain library multierror (Golang 1.20)


A migration information from github.com/hashicorp/go-multierror to the std library errors bundle.

In go1.20 help for “multierrors” was added.

Why migrate? #

Migrating from group go modules to plain library implementations is sort of all the time a no brainer if it offers like for like performance.

Packages within the core go commonplace library resembling errors are coated by the go1.0 backwards compatibility assure [0].
Due to this they’re additionally assured to be supported with safety fixes and different patches.

APIs #

go-multierror #

go-multierror follows the same API to how slices are appended to in go.

Playground: https://go.dev/play/p/DrfOauIC1Ou

var end result error

if err := step1(); err != nil {
end result = multierror.Append(end result, err)
}
if err := step2(); err != nil {
end result = multierror.Append(end result, err)
}
if end result != nil {
fmt.Printf("some error: %v", end result)
}

multierror.Append returns a *multierror.Error which could be additional appended to. And if a multierror is appended to a different, they are going to be flattened to make a flat listing of errors.

errors.Be a part of #

The usual library implementation is as a brand new perform within the errors bundle.

func Be a part of(errs ...error) error

And a brand new unexported interface.

interface { Unwrap() []error }

Playground: https://go.dev/play/p/D7gFVsBwIbg

err1 := step1()
err2 := step2()
err := errors.Be a part of(err1, err2)
if err != nil {
return fmt.Error("some error: %w", err)
}

Variations #

Though at a excessive degree the APIs are comparable, there’s one massive distinction which is that errors.Be a part of doesn’t flatten different “joined” errors.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments