SoFunction
Updated on 2025-03-05

Syntax and examples of formatted output in Go language

Format is very commonly used in logic. When using formatting functions, pay attention to writing:

(Format style, parameter list…)

  • Format style: string form, formatted verb starts with %.
  • Parameter list: Multiple parameters are separated by commas, and the number must correspond to the number in the format style one by one, otherwise an error will be reported during runtime.

In Go, formatted naming continues with the C language style:

var progress = 2
var target = 8

// Two-parameter formattingtitle := ("%d herbs have been collected, and %d will be required to complete the task", progress, target)

(title)

pi := 3.14159
// Output in the format of the value itselfvariant := ("%v %v %v", "Moon Base", pi, true)

(variant)

// Anonymous structure declaration and assign initial valueprofile := &struct {
    Name string
    HP   int
}{
    Name: "rat",
    HP:   150,
}

("Use '%%+v' %+v\n", profile)

("Use '%%#v' %#v\n", profile)

("Use '%%T' %T\n", profile)

The code output is as follows:

2 herbs have been collected, and 8 more tasks are needed

"Moon Base" 3.14159 true

Use '%+v' &{Name:rat HP:150}

Use '%#v' &struct { Name string; HP int }{Name:"rat", HP:150}

Use '%T' *struct { Name string; HP int } in C language, use %d to represent integer parameters

The following table marks the verbs and functions in some commonly used formatting styles.

verb Function
%v Output according to the original value of the value
%+v Based on %v, expand the structure field name and value
%#v Output values ​​in the Go language syntax format
%T Output the type and value of the Go language syntax format
%% Output % body
%b Integers are displayed in binary
%o Integers are displayed in octal
%d Integers are displayed in decimal
%x Integers are displayed in hexadecimal
%X Integers are displayed in hexadecimal and letter capitalization
%U Unicode characters
%f Floating point number
%p Pointer, hexadecimal display

Summarize

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