Trusted answers to developer questions

What is fmt.Print in Golang?

Free System Design Interview Course

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2024 with this popular free course.

The fmt.Print function in the GO programming language is a function used to print out a formatted string to the console. fmt.Print does not support custom format specifiers, which means only the default formats are used to format the string.

Here, Print is the actual function while fmt is the GO package that stores the definition of this function. So to use this function, you must import the fmt package in your file and access the Print function within using the . notation: fmt.Print

Function definition

The definition of the Print function inside the fmt package is as follows:

Parameters

fmt.Print takes a variable number of arguments. In the function definition above, a ...interface{} refers to the list of all arguments that need to be formatted and printed.

Return values

The fmt.Print function can return two things:

  • count: The number of bytes that were written to the standard output.

  • err: Any error thrown during the execution of the function.

Example

The following example is a simple program where we print out a single string along with an integer value:

package main
import (
"fmt"
)
func main() {
// declaring variables of different datatypes
var message string = "Hello and welcome to "
var year int = 2021
// printing out the declared variables as a single string
fmt.Print(message, year)
}

This example shows you how you can make use of the return values from the fmt.Print function:

package main
import (
"fmt"
)
func main() {
// declaring variables of different datatypes
var message string = "Hello and welcome to Educative \n"
// storing the return values of Print
char_count, error := fmt.Print(message)
if error == nil {
fmt.Print("Print executed without errors and wrote ",char_count, " characters")
}
}

RELATED TAGS

golang

CONTRIBUTOR

Faraz Karim
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?