SoFunction
Updated on 2025-04-14

Detailed explanation of the complete method and sample code of the Go language fmt module

Preface

The following is Go languagefmtA complete detailed explanation and example of the module, covering all core functions:

1. Output function

Writes data to standard output, file, or string.

1. Print / Println / Printf

Function

  • Print: Write standard output without wrapping lines.
  • Println: Write standard output and wrap line.
  • Printf: Format write to standard output.

Example

("Hello, ")        // Output: Hello,("World!")       // Output: World! (line break)("%s %d\n", "Year:", 2023) // Output: Year: 2023 (line wrap)

2. Fprint / Fprintln / Fprintf

Function

Write content to the specified(such as files, network connections).

Example

file, _ := ("")
(file, "Hello ")     // Write file content: Hello(file, "World!")   // Write file content: World! (line wrap)(file, "Value: %d", 100) // Write file content: Value: 100

3. Sprint / Sprintln / Sprintf

Function

Format the content as a string and return.

Example

s1 := ("Hello", 123)       // s1 = "Hello123"
s2 := ("World!")         // s2 = "World!\n"
s3 := ("Value: %d", 100)  // s3 = "Value: 100"

2. Input function

Read data from standard input, file, or string.

1. Scan / Scanln / Scanf

Function

  • Scan: Read from standard input, separated by spaces.
  • Scanln: Reading to the newline character stops.
  • Scanf: Read by format string.

Example

var a int
var b string

// Input: 10 ABC(&a, &b)      // a=10, b="ABC"

// Input: 20 XYZ\n(&a, &b)    // a=20, b="XYZ"

// Input: Number: 30("Number: %d", &a) // a=30

2. Fscan / Fscanln / Fscanf

Function

From the specifiedRead data (such as a file).

Example

file, _ := ("")
var x int
var y string

// File content: 100 Golang(file, &x, &y)    // x=100, y="Golang"

// File content: 200 Rust\n(file, &x, &y)  // x=200, y="Rust"

// File content: Value: 300(file, "Value: %d", &x) // x=300

3. Sscan / Sscanln / Sscanf

Function

Parses data from strings.

Example

str := "404 Not Found"
var code int
var msg string

(str, &code, &msg)     // code=404, msg="Not"
("500 Error\n", &code, &msg) // code=500, msg="Error"
("Status: 200 OK", "Status: %d %s", &code, &msg) // code=200, msg="OK"

3. Format verbs

Commonly used formatted placeholders (partial):

verb illustrate Example
%v Default format %v → {Alice 30}
%d Decimal integers %d → 25
%f Floating point number %f → 3.141593
%s String %s → “hello”
%t Boolean value %t → true
%p Pointer address %p → 0xc0000a
%T type %T → int

4. Other functions

1. Errorf

Function

Generate a formatting error.

Example

err := ("Invalid user ID: %d", -1)
// () = "Invalid user ID: -1"

2. Formatter and Stringer interfaces

Function

Format behavior of custom types.

Example

type User struct {
    Name string
    Age  int
}

// Implement Stringer interfacefunc (u User) String() string {
    return ("%s (%dage)", , )
}

// Implement the Formatter interfacefunc (u User) Format(f , verb rune) {
    if verb == 'v' {
        (f, "User{Name:%s, Age:%d}", , )
    }
}

u := User{"Bob", 30}
(u)        // Output: Bob (30 years old)("%v", u)   // Output: User{Name:Bob, Age:30}

5. Things to note

  • Error handlingScanSeries functions return the number of items and errors that were successfully parsed.
    n, err := (&a, &b)
    if err != nil {
        ("Input error:", err)
    }
    
  • performance: When string splicing is frequently used, it is preferred.Rather thanSprintf

6. Complete function list

Function signature Function description
Print(a ...any) (n int, err error) Standard output
Println(a ...any) (n int, err error) Standard output and line break
Printf(format string, a ...any) (n int, err error) Format output
Fprint(w , a ...any) (n int, err error) Write
Sprint(a ...any) string Returns the formatted string
Errorf(format string, a ...any) error Generate formatting error

By masteringfmtPackage method can efficiently handle input and output, string formatting and error generation.

This is all about this article about the Go language fmt module. For more detailed explanations of the Go language fmt module, please search for my previous articles or continue browsing the following related articles. I hope everyone will support me in the future!