Common Functions in the fmt Package
In the first Go program, we used the Println()
function in the fmt
package for output.
The fmt
package is one of the most commonly used packages in Go. It is usually used for formatting output or input. Let's introduce some of its most commonly used output functions through an example.
In Go, there are three types of output functions: Print()
function, Println()
function, and Printf()
function, each with different functions. Let's explain them through an example.
Create a new fmt.go
and enter the following code:
package main
import "fmt"
func main() {
// Standard output
fmt.Print("hello")
fmt.Print("world")
// Println adds a newline character after the standard output
fmt.Println()
fmt.Println("labex")
// Printf provides formatted output
fmt.Printf("%s\n", "Hangzhou")
}
First, we used the standard output Print()
function to output hello
and world
separately. Although they are displayed on two lines, they are actually one line in the terminal. Print()
directly outputs the string inside the function without line breaks or formatted outputs.
In the second part of the code, we used the Println
function. The ln
at the end stands for line
, which means to output the string to the standard output and then add a newline character. We used an empty Println
function to add a line break first, and then we used a standardized output to output the labex
string and add a line break.
In the third part, we used the formatted output Printf
function. The f
at the end stands for format
. We output the string type variable after the string placeholder %s
. At the end, we also used \n
for a line break.
Now let's summarize:
Function |
Standard Output |
Line Break |
Formatted Output |
Print |
â |
à |
à |
Println |
â |
â |
à |
Printf |
à |
à |
â |
In addition to the commonly used output functions, the fmt
package also includes a series of functions for input, error output, etc., which will be explained in later experiments.