Converting Error to String in Go Lang

In Golang, fmt.Println(err) can print out the error err. But how to convert an error to a string explicitely?

In Go, the error type is an interface type that has an interface

type error interface {
    Error() string
}

An error variable represents any value that can describe itself as a string.

Ref: https://golang.org/pkg/builtin/#error

So, for an error err, you can call

err.Error()

to get a string representing err.

For example, the errorString type from errors package of Go lang:

// errorString is a trivial implementation of error.
type errorString struct {
    s string
}

func (e *errorString) Error() string {
    return e.s
}

The Go lang’s fmt package formats an error value by calling its Error() string method.

Eric Ma

Eric is a systems guy. Eric is interested in building high-performance and scalable distributed systems and related technologies. The views or opinions expressed here are solely Eric's own and do not necessarily represent those of any third parties.

6 comments:

  1. Today is 03 August 2020 and still your post is saving people like me, Thanks for sharing!!!
    May Jesus bless you dude!

Leave a Reply

Your email address will not be published. Required fields are marked *