SoFunction
Updated on 2025-03-03

Detailed explanation of the use of Go language output function

Go has three functions for outputting text:

  • Print()
  • Println()
  • Printf()

The Print() function prints its parameters in its default format.

Example

Print values ​​of i and j:

package main
import "fmt"
func main() {
var i, j string = "Hello", "World"
(i)
(j)
}

result:

HelloWorld

Example

If we want to print parameters in a new line, we need to use\n

package main
import "fmt"
func main() {
var i, j string = "Hello", "World"
(i, "\n")
(j, "\n")
}

result:

Hello World

hint:\nCreate a new line.

Example

We can also use only one Print() to print multiple variables.

package main
import "fmt"
func main() {
var i, j string = "Hello", "World"
(i, "\n", j)
}

result:

Hello World

Example

If we want to add spaces between string parameters, we need to use " ":

package main
import "fmt"
func main() {
var i, j string = "Hello", "World"
(i, " ", j)
}

result:

Hello World

Example

If the argument is neither a string nor an integer, Print() inserts spaces between the arguments:

package main
import "fmt"
func main() {
var i, j = 10, 20
(i, j)
}

result:

10 20

The Println() function is similar to the Print() function, with the difference being that spaces are added between the parameters and newlines are added at the end:

Example

package main
import "fmt"
func main() {
var i, j string = "Hello", "World"
(i, j)
}

result:

Hello World

Printf() function

The Printf() function first formats its parameters based on the given formatting placeholder and then prints them.

Here we will use two formatted placeholders:

  • %vValues ​​used to print parameters
  • %TTypes of parameters used to print

Example

package main
import "fmt"
func main() {
var i string = "Hello"
var j int = 15
("The value of i is: %v, type: %T\n", i, i)
("The value of j is: %v, type: %T", j, j)
}

result:

The value of i is: Hello, type: string j is: 15, type: int

This is the end of this article about the detailed explanation of the use of Go language output functions. For more related Go output functions, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!