The fmt.Println
function in the GO programming language is a function used to print out a formatted string
to the console. fmt.Println
does not support custom format specifiers, which means only the default formats are used to format the string
. fmt.Println
also appends a newline character at the end of the string.
Here Println
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 Println
function within using the .
notation: fmt.Println
The definition of the Println
function inside the fmt
package is as follows:
fmt.Println
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.
The fmt.Println
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.
The following example helps as a simple program where we print out a single string
along with an integer value:
package mainimport ("fmt")func main() {// declaring variables of different datatypesvar message string = "Hello and welcome to"var year int = 2021// printing out the declared variables as a single stringfmt.Println(message, year)}
The following example shows us the effects of the new line character fmt.Println
appends to the final string. All the subsequent strings printed after the first one is on a different line:
package mainimport ("fmt")func main() {// declaring variables of different datatypesvar message string = "Hello and welcome to"var year int = 2021// printing out the same message 3 time without// explicitly using the newline characterfmt.Println(message, year)fmt.Println(message, year)fmt.Println(message, year)}
This example shows you how you can use the return values from the fmt.Println
function:
package mainimport ("fmt")func main() {// declaring variables of different datatypesvar message string = "Hello and welcome to Educative"// storing the return values of Printlnchar_count, error := fmt.Println(message)if error == nil {fmt.Print("Println executed without errors and wrote ",char_count, " characters")}}
Free Resources