fmt Package Getting Started Guide
I believe that many people start learning Go language with the fmt.Println("Hello World")
on the official website. This article will help you understand what else the fmt
package can do.
In Go language, we often use the fmt package for formatting input and output operations. Although most of the time we only use a few functions like Print..., Sprint..., and Errorf, and only use some common placeholders, it does not mean that we don't need to understand other features of the fmt package.
Overview of the fmt Package#
The fmt package implements formatted input and output functions similar to those in the C language.
Print Series Functions#
func Print(a ...interface{}) (n int, err error)
func Printf(format string, a ...interface{}) (n int, err error)
func Println(a ...interface{}) (n int, err error)
The Print series functions will output the content to the standard output. The Print function directly outputs the content, Printf supports formatted output, and Println adds a newline character after each output.
For example:
fmt.Print("123")
fmt.Printf("%d", 456)
fmt.Print("789")
fmt.Printf("%d\n", 123)
fmt.Println("123")
fmt.Println("456")
Output:
123456789123
123
456
Sprint Series Functions#
func Sprint(a ...interface{}) string
func Sprintf(format string, a ...interface{}) string
func Sprintln(a ...interface{}) string
The Sprint series functions will output the content as a string. The difference is that Sprint directly outputs the content, Sprintf maps the following content to the corresponding placeholders, and Sprintln adds a newline character after the content.
For example:
s1 := fmt.Sprint("123")
s2 := fmt.Sprintf("name:%s,age:%d", "Lixin", 21)
s3 := fmt.Sprintln("456")
fmt.Println(s1, s2, s3)
Output:
123 name:Lixin,age:21 456
Fprint Series Functions#
func Fprint(w io.Writer, a ...interface{}) (n int, err error)
func Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error)
func Fprintln(w io.Writer, a ...interface{}) (n int, err error)
The Fprint series functions will output the content to a variable that implements the io.Writer interface. The common usage is to write content to a file, but it can also output content to the terminal (rarely used).
For example, write content to the standard output:
fmt.Fprintln(os.Stdout, "Write content to the standard output")
fileObj, err := os.OpenFile("./output.txt", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
if err != nil {
panic(err)
}
name := "Lixin"
// Write content to the opened file handle
fmt.Fprintf(fileObj, "Write information to the file\nname: %s\nage: %d", name, 21)
The output is:
Write content to the standard output
The content of the file output.txt
is:
Write information to the file
name: Lixin
age: 21
Errors#
Errorf is similar to Printf, but it returns an error containing the formatted string.
Usually, we return errors like this:
var err error
// ...
return fmt.Errorf("Error: %v", err)
Scan Series Functions#
func Scan(a ...interface{}) (n int, err error)
func Scanf(format string, a ...interface{}) (n int, err error)
func Scanln(a ...interface{}) (n int, err error)
The Scan series functions are used to scan text from standard input and map the corresponding values to the parameters in a... according to the format parameter.
The Scan function separates input values based on spaces, Scanf separates values based on the format, and Scanln stops scanning based on line breaks.
For example:
var name string
var age int
fmt.Scanln(&name, &age)
fmt.Printf("name: %s, age: %d", name, age)
Input Lixin 21
, output:
name: Lixin, age: 21
Example of Scanf:
var name string
var age int
fmt.Scanf("name:%s age:%d", &name, &age)
fmt.Printf("name: %s, age: %d", name, age)
Input name:Lixin age:21
, output:
name: Lixin, age: 21
Fscan Series Functions#
func Fscan(r io.Reader, a ...interface{}) (n int, err error)
func Fscanln(r io.Reader, a ...interface{}) (n int, err error)
func Fscanf(r io.Reader, format string, a ...interface{}) (n int, err error)
The Fscan series functions can read data from standard input, such as input from a file or command line.
If you want to read content from a file:
var s string
f, _ := os.OpenFile("./output.txt", os.O_CREATE|os.O_RDWR, 0644)
reader := bufio.NewReader(f)
fmt.Fscan(reader, &s)
fmt.Printf("The read string is: %s", s)
If the content of the file output.txt
is file.Outputn ame: Lixinage: 21
, the output is The read string is: file.Outputn
, because Fscan uses a space as the default delimiter and cannot recognize the content after the space.
If you want to read content from standard input, you can use the following code:
var s string
reader := bufio.NewReader(os.Stdin)
fmt.Fscan(reader, &s)
fmt.Printf("Your input is: %s", s)
Input Hello, Lixin
, output Your input is: Hello
, because this function cannot recognize spaces.
Fscanln stops scanning based on line breaks, and Fscanf is similar to Scanf, used to map corresponding line breaks. These two functions have similar usage.
In addition, let me mention the ReadString function in the bufio package, which is used to read a line of string from the specified io.Reader until a specified delimiter is encountered. The function signature is as follows:
func (b *Reader) ReadString(delim byte) (string, error)
For example, if you want to read the first line from the file output.txt
and use a space as the delimiter, you can write:
f, _ := os.OpenFile("./output.txt", os.O_RDWR, 0644)
reader := bufio.NewReader(f)
line, err := reader.ReadString(' ')
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("The read string is: %s", line)
If the content of the file output.txt
is file.Outputn ame: Lixinage: 21
, the output is The read string is: file.Outputn
, because ReadString stops reading when it encounters a space.
Sscan Series Functions#
func Sscan(str string, a ...interface{}) (n int, err error)
func Sscanln(str string, a ...interface{}) (n int, err error)
func Sscanf(str string, format string, a ...interface{}) (n int, err error)
Sscan is a function used to read data from a string and format it into the specified variables.
For example:
str := "1 2 3"
var a, b, c int
n, err := fmt.Sscan(str, &a, &b, &c)
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("Read %d numbers, they are: %d,%d,%d", n, a, b, c)
Running this function will output:
Read 3 numbers, they are: 1,2,3
In the fmt
package of Go language, there are some common placeholders that can be used for formatting output. Here are some commonly used placeholders and their usage:
%v
: The general placeholder that can be used to format values of any type. It automatically selects the appropriate format based on the value's type.%d
: Used to format integer types (including signed and unsigned integers).%f
: Used to format floating-point types.%s
: Used to format string types.%t
: Used to format boolean types.%c
: Used to format character types.%p
: Used to format pointer types.
Here are some examples of how to use these placeholders:
name := "Lixin"
age := 21
pi := 3.14159
isStudent := true
fmt.Printf("Name: %s, Age: %d\n", name, age) // Output: Name: Lixin, Age: 21
fmt.Printf("Pi: %.2f\n", pi) // Output: Pi: 3.14
fmt.Printf("Is student: %t\n", isStudent) // Output: Is student: true
In the format string, placeholders are represented by a percent sign %
followed by a letter. Additional parameters can be added after %d
and %f
placeholders to control the formatting. For example, the %f
placeholder can use .2
to limit the floating-point number to two decimal places.
In addition to the Printf
function, other functions like Sprintf
and Fprintf
can also use these placeholders. The Sprintf
function returns the formatted result as a string, while the Fprintf
function writes the formatted result to a specified io.Writer
.
result := fmt.Sprintf("Name: %s, Age: %d", name, age)
fmt.Println(result) // Output: Name: Lixin, Age: 21
file, _ := os.Create("output.txt")
fmt.Fprintf(file, "Name: %s, Age: %d", name, age)
file.Close()
Summary#
These are the common placeholders and usage in the fmt
package. For more details, you can refer to the official website, which provides detailed explanations.