This is the sixth day of my participation in the August More text Challenge. For details, see: August More Text Challenge

This article will share some of the common output methods in the GO language and the differences between them. Basically complete arrangement of the meaning and use of a variety of placeholders

Formatted output

Common Output modes

  • Print: output to the console (does not accept any formatting, which is equivalent to applying % V to each operand)
  • Println: Output to the console and newline
  • Printf: Only formatted strings can be printed. You can print only string variables (not integer variables, integers, etc.)
  • Sprintf: Formats and returns a string without any output
  • Fprintf: to format and output to IO.Writers instead of os.stdout
package main import ( "fmt" "os" ) type point struct { x, Y int} func main() {x := 1 y := "just a test" y := "just a test" Print(x) //Print (y) Print(p) //Print Println(x)// Println.Println(y) Println.Println(p) //Println Printf("%d\t%c\n", z, z) Printf("%d\t%c\n", z, z) Printf("%d\t%c\n", z, z) 97 a (%d = integer, so print the ASCII value of a, Printf(a %s\n", "string") Printf(s) //Sprintf returns: A string returns a formatted string //Fprintf fmt.fprintf (os.stderr, "an %s\n", "error") //FprintfCopy the code

Placeholders detailed explanation

As you can see, Printf, Sprintf, and Fprintf all need to be formatted, and there are various placeholders involved in formatting. The following is a detailed list of the meanings and uses of the placeholders

It is recommended to look at the code sample to understand the meaning of each placeholder. Looking directly at the meaning of the placeholder is more abstract

Example demonstrates

Package main import (" FMT "" OS") type pointA struct {x, y int} func main() {//Go For example, an instance of the point structure is printed here. P := pointA{1, 2} fmt.Printf("%v\n", p) // {1 2} // If the value is a structure, the formatted output of %+v will include the structure's field name. FMT. Printf (" % \ n + v ", p) / / 2} {x: 1 y: / / # % v form output Go grammar representation of the value. For example, the value of the run source code fragment. FMT. Printf (" % # v \ n ", p) / / main point 2} {x: 1, y: / / need to print the value type, use % T. Printf("%T\n", p) // main.point // Formatting Boolean values is simple. Printf("%t\n", true) // There are many ways to format an integer, using %d for standard decimal format. Printf("%d\n", 123) // This output binary representation. Printf("%b\n", 14) // This outputs the corresponding character of the given integer. Printf("%c\n", 33) //%x provides hexadecimal encoding. Printf("%x\n", 456) // There are also many formatting options for floating point types. Use %f for the most basic decimal format. Printf("%f\n", 78.9) //%e and %e format floating-point types into a (slightly different) s&T notation representation. FMT.Printf("%e\n", 123400000.0) FMT.Printf("%e\n", 123400000.0) // Use %s for basic string output. Printf("%s\n", "\"string\"") // Output with double quotes like in Go source code, using %q. Printf("%q\n", "\"string\"") // Like the integer above, the %x output uses a base-16 encoded string with two characters per byte. Printf("%x\n", "hex this") // To print the value of a pointer, use %p. Printf("%p\n", &p) // When printing numbers, you will often want to control the width and accuracy of the output. You can use the number after % to control the output width. The default result is right-aligned and filled in with Spaces. FMT. Printf (" | | | % 6 d % 6 d \ n ", 12, 345) / / you can also specify the output width of floating point, at the same time can also through the width. Precision syntax to specify the precision of the output. FMT. Printf (" | | % 6.2 f % 6.2 f | \ n ", 1.2, 3.45) / / to the alignment, using the logo. FMT. Printf (" % 6.2 f | | % 6.2 f | \ n ", 1.2, 3.45) / / you may also want to control the width of the output of the string, in particular to ensure their alignment when class form output. This is the basic right-aligned width representation. FMT. Printf (" % % 6 s | | | 6 s \ n ", "foo", "b") / / to the left, as well as Numbers, using the logo. FMT. Printf (" % | - 6-6 s | | % s \ n ", "foo", "b") / / so far, we have seen the Printf, it through the OS. Stdout output formatted string. Sprintf formats and returns a string without any output. S := fmt.sprintf ("a %s", "string") fmt.println (s) // You can use Fprintf to format and print to IO.Writers instead of os.stdout. fmt.Fprintf(os.Stderr, "an %s\n", "error") }Copy the code

Universal placeholder

%v is formatted with the default placeholders for each data type (the following shows what the default output placeholders are for each type). %+v adds a field name (such as a structure). %#v goes syntax for the corresponding value of %T goes syntax for the corresponding value of %% is a literal percent sign, not a value placeholderCopy the code

Boolean value related placeholders

% t true or falseCopy the code

Integer values are associated with placeholders

%b binary represents %c the character represented by the corresponding Unicode code point %d Decimal represents % O octal represents % Q the single quoted character literal, which is safely escaped by Go syntax in %x hexadecimal, and the letter form is lowercase A-f %x hexadecimal, Unicode format: U+1234, equivalent to "U+%04X"Copy the code

Placeholders associated with floating point and complex numbers

%b a scientific notation with no decimal part, exponentiated to a power of two, consistent with the 'b' conversion in strconv.FormatFloat. For example, -123456p -78% e scientific notation, for example, -1234.456e+ 78% f has a decimal point but no exponent, For example, 123.456 %g Select %e or %f, depending on the situation, to produce a more compact (zero with no end) outputCopy the code

Slice – related placeholders of strings and bytes

%s String or slice of uninterpreted bytes % Q Double quoted string, safely escaped by Go syntax %x hexadecimal, lowercase letters, two characters per byte %x hexadecimal, uppercase letters, two characters per byteCopy the code

Pointer related placeholders

%p hexadecimal, prefix 0xCopy the code

other

Default format for various data types

Bool: %t int, int8 etc.: %d uint, uint8 etc.: %d, %x if printed with %#v float32, complex64, etc: %g string: %s chan: %p pointer: %pCopy the code

Width and accuracy

Width is the value after %, if not specified, the default value for that value is used, and precision is the value after width, or the default precision for the value to be printed if not specified. For example: % 9.2f, width 9, precision 2

%f: Default width, default precision %9f width 9, default precision %.2f default width, precision %9f width 9, precision 2 %9.f width 9, precision 0Copy the code

Width is the “minimum width necessary “. If the width of the resulting string exceeds the specified width, the specified width becomes invalid. In the case of string % s or floating point % f, precision truncates the length of the data

Func main() {a := 123 fmt.Printf("%1.2d\n", a) //123 Unable to truncate the integer b: = 1.23 FMT) Printf (" % 1.1 f \ n ", b) / / 1.2, accuracy is 1, truncation floating-point data c: = "asdf" FMT. Printf (" % *. * s \ n ", 1, 2, c) / / as, Width and precision inputs are supported with '*', and strings can also be truncated with precision}Copy the code

Other signs

  • + : the plus or minus sign of the total printed value; For %q (%+q) only ASCII encoded characters are guaranteed to be output.
  • – : Left-aligned
  • # : Alternate formats: add leading 0 (%#o) for octal, add leading 0x (%#x) or 0x (%#x) for hexadecimal, remove leading 0x for %p (%#p); For %q, if strconv.CanBackquote returns true, the original (that is, the backquoted) string is printed; If it is a printable character, %U (%#U) will write the Unicode encoding of the character (for example, the character x will print U+0078 ‘x’).
  • “:(space) leave space for omitted signs in values (% d); When a string or slice is printed in hexadecimal (% x, % x), the bytes are separated by Spaces
  • 0: fill leading zeros instead of Spaces; For numbers, this moves the fill behind the plus or minus sign
  • [1] : Reuse the first operand
package main

import "fmt"

func main() {
	o := 0666
	fmt.Printf("%d %[1]o %#[1]o\n", o) // 438 666 0666
	x := int64(0xdeadbeef)
	fmt.Printf("%d %[1]x %#[1]X\n", x)//3735928559 deadbeef 0XDEADBEEF
}
Copy the code

Thanks for the following excellent articles

Go language foundation –Printf format output, Scanf format input detailed explanation

Several formatted outputs used by printf() in Golang

About golang fmt.printf() output formatting

package fmt