How to print error in golang?

Hi Friends 👋,

Welcome To aGuideHub! ❤️

Today, I’m going to show you how to print an error in the golang console, obviously, we will use our "fmt" package to print an error.

The fmt package provides the Println() method that we can use to print errors.

Here, we are also using the "errors" package to generate custom errors.

let’s start the code.

package main
import (
    "errors"
    "fmt"
)

func main() {
  err := errors.New("an error occurred")
  if err != nil {
    fmt.Println(err)
  }
}

When I run the above code, the golang console shows `an error occurred in string datatype, check following image.

print, error, golang

Try it yourself

All the best 👍

Follow me on Twitter