fmt of Go language standard library

1.fmt

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

1.1 output out

1.1.1Print

Print The series function outputs the content to the standard output of the system, with the difference
Print Function to output content directly,
Printf The function supports formatting output strings,
Println The function adds a line break at the end of the output.

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)
package main

import "fmt"

func main()  {
    fmt.Print("Print Output information!")
    name := "vita"
    fmt.Printf("Printf output name:%s\n",name)
    fmt.Println("Println Output information")
}

//Result:
Print Output information!Printf output name:vita
Println Output information

Process finished with exit code 0

1.1.2Fprint

Fprint Series functions output content to a io.Writer Variables of interface type w We usually use this function to write to a file.
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)
package main

import (
    "fmt"
    "os"
)

func main()  {
    //Write to standard output
    fmt.Fprint(os.Stdout,"Fprint Write content to standard output")
    fmt.Fprintln(os.Stdout,"Fprintln Write content to standard output")
    name := "vita"
    fmt.Fprintf(os.Stdout,"Fprintf Write content to standard output name:%s",name)

    fileObj,err := os.OpenFile("./file",os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
    if err != nil{
        fmt.Println("Error opening file, err:",err)
    }
    //Write to file
    fmt.Fprint(fileObj,"Fprint Write content to file")
    fmt.Fprintln(fileObj,"Fprintln Write content to file")
    fmt.Fprintf(fileObj,"Fprintf Write content to file,name:%s",name)
}

//Result:
Fprint Write content to standard output Fprintln Write content to standard output
Fprintf Write content to standard output name:vita
Process finished with exit code 0

1.1.3Sprint

Sprint The series function generates the incoming data and returns a string.
func Sprint(a ...interface{}) string
func Sprintf(format string, a ...interface{}) string
func Sprintln(a ...interface{}) string
package main

import "fmt"

func main()  {
    s1 := fmt.Sprint("Sprint")
    fmt.Println(s1)
    s2 := fmt.Sprintln("Sprintln")
    fmt.Println(s2)
    s3 := fmt.Sprintf("Sprintf,s1:%s",s1)
    fmt.Println(s3)
}

//Result:
Sprint
Sprintln

Sprintf,s1:Sprint

Process finished with exit code 0

1.1.4Errorf

The errorfunction generates a format string based on the format parameter and returns an error containing the modified string.
func Errorf(format string, a ...interface{}) error
 This method is usually used to define the error type.
package main

import "fmt"

func main()  {
    name := "vita"
    err := fmt.Errorf("%s An error was created",name)
    fmt.Printf("value:%v type:%T",err,err)
}

//Result:
value:vita An error was created type:*errors.errorString
Process finished with exit code 0

1.1.5 format placeholders

*printf series functions support format format parameters. In this case, we divide the variables into different types according to the placeholders to facilitate query and memory.

1.1.5.1 general placeholder

package main

import "fmt"

func main()  {
    fmt.Printf("v:%v\n", 100)
    fmt.Printf("v:%v\n", false)
    o := struct{ name string }{"Princeling"}
    fmt.Printf("v:%v\n", o)
    fmt.Printf("+v:%+v\n", o)
    fmt.Printf("#v:%#v\n", o)
    fmt.Printf("T:%T\n", o)
    fmt.Printf("100%%\n")
}

//Result:
v:100
v:false
v:{Princeling}
+v:{name:Princeling}
#v: Struct {name string} {Name: "Little Prince"}
T:struct { name string }
100%

Process finished with exit code 0

1.1.5.2 Boolean

package main

import "fmt"

func main()  {
    fmt.Printf("t:%t\n", false)
    fmt.Printf("v:%v\n", false)

}

//Result:
t:false
v:false

Process finished with exit code 0

1.1.5.3 integer

package main

import "fmt"

func main()  {
    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)
}

//Result:
1000001
A
65
101
41
41

Process finished with exit code 0

1.1.5.4 floating point and complex number

package main

import "fmt"

func main()  {
    f := 12.34
    fmt.Printf("b:%b\n", f)
    fmt.Printf("e:%e\n", f)
    fmt.Printf("E:%E\n", f)
    fmt.Printf("f:%f\n", f)
    fmt.Printf("F:%F\n", f)
    fmt.Printf("g:%g\n", f)
    fmt.Printf("G:%G\n", f)
}

//Result:
b:6946802425218990p-49
e:1.234000e+01
E:1.234000E+01
f:12.340000
F:12.340000
g:12.34
G:12.34

Process finished with exit code 0

1.1.5.5 string and [] byte

package main

import "fmt"

func main()  {
    s := "Princeling"
    fmt.Printf("%s\n", s)
    fmt.Printf("%q\n", s)
    fmt.Printf("%x\n", s)
    fmt.Printf("%X\n", s)
}

//Result:
//Princeling
"Princeling"
e5b08fe78e8be5ad90
E5B08FE78E8BE5AD90

Process finished with exit code 0

1.1.5.6 pointer

package main

import "fmt"

func main()  {
    a := 10
    fmt.Printf("%p\n", &a)
    fmt.Printf("%#p\n", &a)
}

//Result:
0xc00007e000
c00007e000

Process finished with exit code 0

1.1.5.7 width identifier

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

package main

import "fmt"

func main()  {
    n := 12.34
    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)
}

//Result:
12.340000
12.340000
12.34
    12.34
       12

Process finished with exit code 0

1.1.5.8 other flag s

package main

import "fmt"

func main()  {
    s := "Princeling"
    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)
}

//Result:
//Princeling
  //Princeling
//Princeling  
  //Princeling
//Princeling  
   //Xiao Wang
00 Princeling

Process finished with exit code 0

1.2 get input

1.2.1fmt.Scan

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

import "fmt"

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

//Enter the corresponding value of name, age, and bound in the terminal
lili 23 true
//Scan result Name: Lili age: 23 bound: true 

Process finished with exit code 0

1.2.2fmt.Scanf

func Scanf(format string, a ...interface{}) (n int, err error)
Scanf scans the text from the standard input, reads the value separated by the blank character according to the format specified by the format parameter, and saves it in the parameter of this function.
This function returns the number of data successfully scanned and any errors encountered.
Be careful:
Scanf is different from Scan. Scanf has specific input content format for input data. Only input data according to the format can Scan successfully and store it in variables.
package main

import "fmt"

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

//Result:
1:lili 2:27 3:true
//Scan result name: age:0 married:false 

Process finished with exit code 0

1.2.3fmt.Scanln

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

import "fmt"

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

//Result:
lili 27 true
//Scan result Name: Lili age: 27 bound: true 

Process finished with exit code 0

1.2.4bufio.NewReader

Sometimes, we want to get the input completely, and the input may contain spaces. In this case, bufio package can be used.
package main

import (
    "bufio"
    "fmt"
    "os"
    "strings"
)

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

//Result:
//Please input: ww qq aa
"ww qq aa"

Process finished with exit code 0

1.2.5Fscan series

These functions are similar to fmt.Scan, fmt.Scanf and fmt.Scanln, but they read data not from standard input but from io.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)
package main

import (
    "fmt"
    "os"
)

func main() {
    var (
        name string
        age int
    )
    fileObj, err := os.OpenFile("./xx.txt", os.O_CREATE|os.O_RDONLY|os.O_APPEND, 0644)
    if err != nil {
        fmt.Println("Error opening file, err:", err)
        return
    }
    fmt.Fscan(fileObj,&name,&age)
    fmt.Println(name,age)
}

//Result:
lili 27

Process finished with exit code 0

1.2.6Sscan series

These functions are similar to fmt.Scan, fmt.Scanf and fmt.Scanln, but they read data not from standard input but from 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)
package main

import "fmt"

func main() {
    var (
        name string
        age int
    )
    fmt.Sscan("lili 27",&name,&age)
    fmt.Println(name,age)
}

//Result:
lili 27

Process finished with exit code 0

Tags: Go less C

Posted on Thu, 06 Feb 2020 04:36:36 -0800 by epilator