SoFunction
Updated on 2025-03-05

Analysis of println and difference in Golang

Printing data in Golang is usually done using the () method, or the built-in println() method can be used. You may have used these two methods, what is the difference?

println()

Let's first look at the comments of the println() method:

// The println built-in function formats its arguments in an
// implementation-specific way and writes the result to standard error.
// Spaces are always added between arguments and a newline is appended.
// Println is useful for bootstrapping and debugging; it is not guaranteed
// to stay in the language.

It can be seen that println() is a built-in method and belongs to the builtin package (the builtin package is a pre-declared package of Golang and can be used without import). You can pass in multiple Type types (pointer, channel, func, interface, map and slice types) parameters, and write the result to a standard error. Mainly used for debugging, this method is not guaranteed to be retained in future Golang versions.

()

Let's look at the comments in ():

// Println formats using the default formats for its operands and writes to standard output.
// Spaces are always added between operands and a newline is appended.
// It returns the number of bytes written and any write error encountered

It can be seen that () belongs to the fmt package, and multiple interface-type parameters can be passed in and the result can be written to standard output. Returns two parameters - the number of bytes written and the error.

The difference between println() and ()

The following differences can be seen through the above comments and instructions:

  • The package belongs to is different. println() belongs to the builtin package, and () belongs to the fmt package.

  • The output method is different. println() outputs to standard error (STDERR), and () outputs to marked output (STDOUT).

  • The return value is different. println() has no return value, and () has two return values ​​- the number of bytes written and the error.

  • println() output may not be consistent with the expected result order, while () output is exactly consistent with the expected result (this characteristic is determined by the standard error and the characteristics of the standard output).

  • println() cannot pass parameters of array and structure type.

  • For parameters of combination types, the result output by println() is the address of the parameter, while the result output by () is the literal.

Is there any difference between println and Golang? That’s all for the article. For more related Golang println and different content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!