how to convert string to error in golang?

Hi Friends 👋,

Welcome To aGuideHub! ❤️

To convert string to error in golang, just use errors.New() method and pass your string, it will convert string into error.


Follow the below tutorial if you are struggling with installing GO in windows.

https://aguidehub.com/blog/how-to-install-golang-in-windows/


Today, I will show you how do I convert string to error in golang, as above mentioned I’m going to use errors.New() way.

The errors package provide New() method.

Let’s start our Golang convert string to error example

Convert whole string into error example

main.go

package main

import (
    "errors"
    "fmt"
)

func main() {
    s := "Custom Error Message"
    err := errors.New(s)
    fmt.Println(err)
}

In the above example, we have converted string to error and printed in golang console. let’s check the output.

Output

Custom Error Message

Try it Yourself

I hope it helps you, 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.

Related Posts