fmt in Golang standard library

fmt in Golang standard library

fmt package implements formatted I/O similar to C language printf and scanf. It is mainly divided into two parts: output content and obtain input content.

1. Outward output

The standard library fmt provides the following output correlation functions.

Print

Print series functions will output the content to the standard output of the system. The difference is that print function directly outputs the content, Printf function supports formatting the output string, and Println function will add a newline character at the end of the output content.

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)

Take a simple example:

func main() {
    fmt.Print("Print the information at the terminal.")
    name := "Withered vine"
    fmt.Printf("I am:%s\n", name)
    fmt.Println("Print a separate line of display at the terminal")
}

Execute the above code output:

    Print the information at the terminal. I am: Kuteng
    Print a separate line of display at the terminal

Fprint

The Fprint series of functions will output the content to an IO We usually write the contents of the variable writer in the w interface.

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)

for instance:

// Write content to standard output
fmt.Fprintln(os.Stdout, "Write content to standard output")
fileObj, err := os.OpenFile("./xx.txt", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
if err != nil {
    fmt.Println("Error opening file, err:", err)
    return
}
name := "Withered vine"
// Writes to an open file handle
fmt.Fprintf(fileObj, "Write the following information into the file:%s", name)

Note that as long as io All types of writer interface support writing.

Sprint

The Sprint series of functions will generate the incoming data and return a string.

func Sprint(a ...interface{}) string
func Sprintf(format string, a ...interface{}) string
func Sprintln(a ...interface{}) string

The simple example code is as follows:

s1 := fmt.Sprint("Withered vine")
name := "Withered vine"
age := 18
s2 := fmt.Sprintf("name:%s,age:%d", name, age)
s3 := fmt.Sprintln("Withered vine")
fmt.Println(s1, s2, s3)

Errorf

The errorffunction generates a formatted string based on the format parameter and returns an error containing the string.

func Errorf(format string, a ...interface{}) error

This is usually used to customize the error type, for example:

err := fmt.Errorf("This is a mistake")

2. Format placeholder

*printf series functions support format parameters. Here, we divide the variable types to be replaced by placeholders to facilitate query and memory.

Generic placeholder

placeholder explain
%vDefault format representation of values
%+vSimilar to%v, but the field name will be added when outputting the structure
%#vGo syntax representation of value
%TType of print value
%%Percent sign

The example code is as follows:

fmt.Printf("%v\n", 100)
fmt.Printf("%v\n", false)
o := struct{ name string }{"Withered vine"}
fmt.Printf("%v\n", o)
fmt.Printf("%#v\n", o)
fmt.Printf("%T\n", o)
fmt.Printf("100%%\n")

The output results are as follows:

100
false
{Withered vine}
struct { name string }{name:"Withered vine"}
struct { name string }
100%

Boolean type

placeholder explain
%ttrue or false

integer

placeholder explain
%bExpressed as binary
%cThe unicode code value corresponding to this value
%dExpressed in decimal
%oExpressed in octal
%xExpressed in hexadecimal, using a-f
%XExpressed in hexadecimal, using A-F
%UExpressed in Unicode format: U+1234, equivalent to "U+%04X"
%qThe value corresponds to the literal value of go syntax character enclosed in single quotation marks, which will be expressed by safe escape if necessary

The example code is as follows:

n := 65
fmt.Printf("%b\n", n)
fmt.Printf("%c\n", n)
fmt.Printf("%d\n", n)
fmt.Printf("%o\n", n)
fmt.Printf("%x\n", n)
fmt.Printf("%X\n", n)

The output results are as follows:

    1000001
    A
    65
    101
    41
    41

Floating point number and complex number

placeholder explain
%bScientific counting method without decimal part and binary index, such as - 123456p-78
%eScientific counting method, such as -1234.456e+78
%EScientific counting method, such as -1234.456E+78
%fThere is a fractional part but no exponential part, such as 123.456
%FEquivalent to% f
%gUse% e or% f format according to the actual situation (for more concise and accurate output)
%GUse% E or% F format according to the actual situation (for more concise and accurate output)

The example code is as follows:

f := 12.34
fmt.Printf("%b\n", f)
fmt.Printf("%e\n", f)
fmt.Printf("%E\n", f)
fmt.Printf("%f\n", f)
fmt.Printf("%g\n", f)
fmt.Printf("%G\n", f)

The output results are as follows:

    6946802425218990p-49
    1.234000e+01
    1.234000E+01
    12.340000
    12.34
    12.34

String and [] byte

placeholder explain
%sDirectly output string or [] byte
%qThe value corresponds to the literal value of the go syntax string enclosed in double quotation marks. If necessary, it will be expressed by safe escape
%xEach byte is represented by a two character hexadecimal number (using a-f)
%XEach byte is represented by a two character hexadecimal number (using A-F)

The example code is as follows:

    s := "Withered vine"
    fmt.Printf("%s\n", s)
    fmt.Printf("%q\n", s)
    fmt.Printf("%x\n", s)
    fmt.Printf("%X\n", s)

The output results are as follows:

    Withered vine
    "Withered vine"
    e69eafe897a4
    E69EAFE897A4

Pointer

placeholder explain
%pExpressed in hexadecimal and preceded by 0x

The example code is as follows:

a := 18
fmt.Printf("%p\n", &a)
fmt.Printf("%#p\n", &a)

The output results are as follows:

    0xc000054058
    c000054058

Width identifier

The width is specified by a decimal number immediately following the percent sign. If the width is not specified, the value is not filled in unless necessary. The precision is specified by the (optional) width followed by a decimal number followed by a dot. If no precision is specified, the default precision is used; If the point number is not followed by a number, the precision is 0. Examples are as follows

placeholder explain
%fDefault width, default precision
%9fWidth 9, default precision
%.2fDefault width, precision 2
%9.2fWidth 9, accuracy 2
%9.fWidth 9, accuracy 0

The example code is as follows:

n := 88.88
fmt.Printf("%f\n", n)
fmt.Printf("%9f\n", n)
fmt.Printf("%.2f\n", n)
fmt.Printf("%9.2f\n", n)
fmt.Printf("%9.f\n", n)

The output results are as follows:

    88.880000
    88.880000
    88.88
        88.88
           89

Other falls

placeholder explain
'+'Always output the sign of the value; For% q (% + q), the output of all ASCII characters will be generated (through escape);
' 'For numeric values, the positive number is preceded by a space and the negative number is preceded by a minus sign; When% X or% X is used for a string (% X or% x), spaces are added between each printed byte
'-'Fill in blank space on the right side of the output instead of the default left side (i.e. switch from the default right alignment to left alignment);
'#'Add 0 (% #o) before the octal number and 0x (% #x) or 0x (% #x) before the hexadecimal number. The pointer will remove the preceding 0x (% #p) for% Q (% #q) and for% U (% #u), and the go literal enclosed in spaces and single quotation marks will be output;
'0'Fill with 0 instead of spaces. For numeric types, the filled 0 will be placed after the sign;

for instance:

s := "Withered vine"
fmt.Printf("%s\n", s)
fmt.Printf("%5s\n", s)
fmt.Printf("%-5s\n", s)
fmt.Printf("%5.7s\n", s)
fmt.Printf("%-5.7s\n", s)
fmt.Printf("%5.2s\n", s)
fmt.Printf("%05s\n", s)

The output results are as follows:

    Withered vine
       Withered vine
    Withered vine
       Withered vine
    Withered vine
       Withered vine
    000 Withered vine

3. Get input

FMT is available under the Go language package Scan,fmt.Scanf,fmt.Scanln three functions, which can obtain user input from standard input during program operation.

fmt.Scan

The signature of the function is as follows:

func Scan(a ...interface{}) (n int, err error)
  • Scan scans the text from the standard input, reads the value separated by the blank character, and saves it to the parameters passed to this function. The newline character is regarded as a blank character.
  • This function returns the number of successfully scanned data and any errors encountered. If the number of data read is less than the provided parameters, an error report reason will be returned.

Specific code examples are as follows:

func main() {
    var (
        name    string
        age     int
        married bool
    )
    fmt.Scan(&name, &age, &married)
    fmt.Printf("Scanning results name:%s age:%d married:%t \n", name, age, married)
}

Compile the above code and execute it at the terminal. Input Kuteng, 18 and false at the terminal in turn, separated by spaces.

    $ ./scan_demo 
    Kuteng 18 false
    Scanning results name:Withered vine age:18 married:false

fmt.Scan scans the data entered by the user from the standard input, and stores the data separated by blank characters into the specified parameters respectively.

fmt.Scanf

The function signature is as follows:

func Scanf(format string, a ...interface{}) (n int, err error)
  • Scanf scans the text from the standard input, reads the values separated by whitespace according to the format specified by the format parameter, and saves them to the parameters passed to this function.
  • This function returns the number of successfully scanned data and any errors encountered.

Code examples are as follows:

func main() {
    var (
        name    string
        age     int
        married bool
    )
    fmt.Scanf("1:%s 2:%d 3:%t", &name, &age, &married)
    fmt.Printf("Scanning results name:%s age:%d married:%t \n", name, age, married)
}

Compile the above code and execute it at the terminal. Input Kuteng, 18 and false in the specified format at the terminal.

    $ ./scan_demo 
    1:Kuteng 2:18 3:false
    Scanning results name:Withered vine age:18 married:false

fmt.Scanf is different from FMT Scan simply takes a space as the separator of input data, FMT Scanf specifies the specific input content format for the input data. Only the input data according to the format will be scanned and stored in the corresponding variable.

For example, let's enter FMT. FMT in the way separated by spaces in the previous example Scanf cannot scan the input data correctly.

    $ ./scan_demo 
    Kuteng 18 false
    Scanning results name: age:0 married:false

fmt.Scanln

The function signature is as follows:

func Scanln(a ...interface{}) (n int, err error)
  • It is similar to Scan when Scan stops scanning. The last data must be followed by a line break or reach the end position.
  • This function returns the number of successfully scanned data and any errors encountered.

Specific code examples are as follows:

    func main() {
        var (
            name    string
            age     int
            married bool
        )
        fmt.Scanln(&name, &age, &married)
        fmt.Printf("Scanning results name:%s age:%d married:%t \n", name, age, married)
    }

Compile the above code and execute it at the terminal. Input Kuteng, 18 and false at the terminal in turn, separated by spaces.

    $ ./scan_demo 
    Kuteng 18 false
    Scanning results name:Withered vine age:18 married:false

fmt.Scanln finishes scanning when it encounters a carriage return. This is commonly used.

bufio.NewReader

Sometimes we want to get the input completely, and the input may contain spaces. In this case, we can use the bufio package. The example code is as follows:

func bufioDemo() {
    reader := bufio.NewReader(os.Stdin) // Generate read objects from standard input
    fmt.Print("Please enter:")
    text, _ := reader.ReadString('\n') // Read line feed
    text = strings.TrimSpace(text)
    fmt.Printf("%#v\n", text)
}

Fscan series

The functions of these functions are similar to FMT Scan,fmt.Scanf,fmt.Scanln has three functions, but they do not read data from standard input, but from Io Read data from reader.

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)

Sscan series

The functions of these functions are similar to FMT Scan,fmt.Scanf,fmt.Scanln three functions, but they do not read data from standard input, but from a specified string.

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)

Keywords: Go Back-end

Added by keeve on Sun, 06 Mar 2022 17:15:37 +0200