ADVERTISEMENT
ADVERTISEMENT

Golang fmt.Errorf() Function with Examples

Golang | fmt.Errorf() Function: Here, we are going to learn about the Errorf() function of the fmt package with its usages, syntax, and examples.
Submitted by IncludeHelp, on October 07, 2021

fmt.Errorf()

In Go language, the fmt package implements formatted I/O with functions analogous to C's printf() and scanf(). The Errorf() function is an inbuilt function of the fmt package which is used to format according to a format specifier and returns the string as a value that satisfies error, i.e., the Errorf() function allows us to use formatting features to create descriptive error messages.

It accepts two parameters (format string, a ...interface{}) and returns the formatted string as a value that satisfies the error.

Syntax:

func Errorf(format string, a ...interface{}) error

Parameter(s):

  • format : The string and format verbs (placeholder values) to format the error message.
  • a : A custom type that is used to specify a set of one or more method signatures, here we can provide a set of the variables, constants, functions, etc.

Return Value:

The return type of the fmt.Errorf() function is an error, it returns the formatted string as a value that satisfies the error.

Example 1:

// Golang program to demonstrate the
// example of fmt.Errorf() function

package main

import (
	"fmt"
)

func main() {
	const name, roll = "Alex", 21

	// Formatting error string
	err := fmt.Errorf("Student %q [Roll: %d] not found", name, roll)

	fmt.Println(err.Error())
}

Output:

Student "Alex" [Roll: 21] not found

Example 2:

// Golang program to demonstrate the
// example of fmt.Errorf() function

package main

import (
	"fmt"
	"os"
	"time"
)

func main() {
	// Format error string with process id & time
	err := fmt.Errorf(
		"Error occurred [%d at %v]",
		os.Getpid(), time.Now())

	fmt.Println(err.Error())
}

Output:

Error occurred [12 at 2009-11-10 23:00:00 +0000 UTC m=+0.000000001]

Golang fmt Package »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.