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 👍

Premium Content

You can get all the below premium content directly in your mail when you subscribe us

Books

Portfolio Template

View | Get Source Code

Cheat Sheets

Cheat Sheets Books are basically Important useful notes which we use in our day-to-day life.

I'm working on some more Cheat Sheets book on Jquery, TypeScript, React js and for other languages. I will send it once it's completed.

Stay tuned working on React Js Cheat Sheets Book

Related Posts