📜  GoLang 中的 fmt 包

📅  最后修改于: 2021-10-25 02:19:42             🧑  作者: Mango

先决条件: GoLang 中的包和 GoLang 中的导入

从技术上讲,包本质上是用于某些特定目的的源代码容器。包是非常重要的,因为在从最基本的程序到高级复杂代码的所有程序中,都会使用这些包。一个包确保没有代码重复,并且主要代码以结构良好的方式尽可能简洁。 Go 为用户提供了各种内置包,以便他们可以使用预定义的基本功能包轻松进行编码。 “ fmt ”包中的此类包之一。 fmt代表格式包。该包允许格式化基本字符串、值或任何内容并打印它们或从控制台收集用户输入,或使用编写器写入文件,甚至打印自定义的花哨错误消息。这个包是关于格式化输入和输出的。

不管你安装了什么系统,找到你的 $GOPATH,然后访问你系统上的“$GOPATH/src/fmt/” 。您将在此特定目录中找到以下包文件。好吧,我们可以说这些文件都属于 fmt 包。

Gopath 中的 fmt 包文件

该图像显示了位于 PC 上“$GOPATH/src/fmt/”目录中的所有文件

让我们看看它为用户提供的功能以及每个函数的简要说明:

     FUNCTIONS    

DESCRIPTION

Print

Print simply prints whatever input it receives as it is on theoutput console screen, beginning from the current cursor positionwithout appending any space or newlines unless explicitly coded.Apart from printing, it returns two values: the no of bytes writtenand error message in case any write error is encountered.

Printf

Printf formats the input string as the user’s choice and then printsthe formatted string onto the output console beginning from thecurrent cursor position without appending any space or newlinesunless explicitly coded. Apart from printing, it returns two values:the number of bytes written and error message in case any erroris encountered.

Println

Println works the same as print function except that it appends newline at the end of the input string and so whatever the output is, in the end, the cursor will move to the next line. Also in case, any variables are added to the input string then this function will ensure that the variables are separated by a space in between. Apart from printing, it returns two values: the no of bytes written and error message in case any write error is encountered.

Sprint

Sprint functions the same way as Print does. The only differenceis that Sprint returns the input string instead of printingon the output console.

Sprintf

Sprintf functions the same way as Printf does. The only differenceis that Sprintf returns the formatted input string insteadof printing on the output console.

Sprintln

Sprintln functions the same way as Println does. the only difference is that Sprintln returns the input stringinstead of printing on the output console.

Fprint

Unlike other print functions, the Fprint does not read or print anything on the console. Fprint formats the input string as per the default formatting and writes the formatted input string into the input file. Whenever two variables are encountered, space is automatically added in between by fprint. Apart from writing into the file, fprint returns two values: no. of bytes written& error message (if any error occurs).

Fprintf

Just similar to fprint but one difference that draws a line between the two is that fprintf formats according to the specified format and does not format according to the default formatting.Fprintf then writes the formatted input string into the file using. Apart from writing into the file, fprintf returns two values: no. of bytes are written and an error message (if any error occurs).

Fprintln

Works exactly the same as fprint. One extra point in Fprintln is thata newline is appended. The formatted input string will then bewritten into the mentioned file with the help of a writer. Apartfrom writing into the file, fprintln returns two values: no. of byteswritten and an error message (if any error occurs).

Scan

Scan collects input from the standard console, and stores this inputin successive arguments. Values that are separated by space ornewlines are treated as multiple values. These are stored inmultiple arguments. Apart from the on-screen scanning work,Scan also returns two values: no. of bytes read from consoleand an error message (if any).

Scanf

Just like the scanf in C language, where a format specifier ismentioned and then the address of the variable where theinput value is to be stored, Scanf in Go scans text read fromstandard input, and stores it in the arguments as per the specifiedformat. Apart from the on-screen scanning work, Scan alsoreturns two values: no. of bytes read from console andan error message (if any).

Scanln

Scanln works similar to Scan, but scanln stops scanning at anewline. Meaning that the last input character should befollowed by a newline for Scanln to stop scanning. Itmay as well be an End of file, no content no scan!

Sscan

Sscan works similar to scan except the difference that sscancollects input as the argument string and not the inputfrom the console screen in default formatting. And just likethe others it returns the two values: no of bytes & error message (if any).

Sscanf

Sscanf works similar to scanf except the difference that sscanfcollects input as the argument string and not the input fromthe console screen in mentioned formatting.

Sscanln

Sscanln is similar to Sscan but sscanln stops scanning at anewline. Meaning that the last input character should befollowed by a newline for Sscanln to stop scanning. Itmay as well be an End of file, no content no scan!

Fscan

Unlike other scan functions which collect input from useror the program console, in default formatting, Fscanreads content or text from the input file and returns theno of items parsed. It reads character wise, progressdirection depends on the pointer location you provide.

Fscanf

Fscanf works similar to fscan. The only difference is that fscanf reads from reader in the specified format rather than following the default formatting. The match-case is sensitive to whole words, spaces and newlines and hence, the argument string and text string must match entirely. Fscanf, apart from reading the characters, also returns the no of items parsed.

Fscanln

Fscanln is similar to Fscan but  Fscanln stops scanning at a newline. Meaning that the last input character should be followed by a newline for Fscanln to stop scanning. Itmay as well be an End of file, no content no scan!

Errorf

Errorf formats according to the mentioned format specifier and assigns this formatted string to a variable. This is the error message. This function allows you to printcustomized error messages, as per the user’s will, and print it to console as an error message.

除了函数之外,Go 在其包中还有一些内置接口。 “fmt”包由以下接口组成。以下描述来自Go官网,您可以点击这里了解更多。

        TYPES        

DESCRIPTION

Formatter

Formatter is an interface that makes custom formattingpossible. Calling format would be something likePrintf(f), Fprintf(f), Sprintf(f) etc.. to generate a customformatted output on the console.

GoStringer

Any code-value that has a GoString method directlyimplements the GoStringer interface implicitly.

ScanState

The ScanState interface holds declaration of valuablefunctions like:ReadRune, UnreadRune, SkipSpace, Token, Width & Read.Basically they tell more about the state of the custom scanner.

Scanner

All the scanning functions that we use – Scan, Scanfand Scanln etc… whenever used make a call to thescanner interface. The scanner interface makes it possiblefor us to collect input through console and/orinput argument strings.

State

It represents the state of the printer that’s passedto specific formats. It also holds informationabout flags and available options for the argumentstring’s format specifier.

Stringer

Any value that holds a string method (that makes the conversion of string argument into output possible)and uses the default formatting, directly implements the Stringer interface. For instance: Print, Sprint, etc.

所以基本上,在 Go 中实现任何接口,我们刚刚了解到我们不必显式做任何事情。而是调用特定方法自动为用户实现接口。并且正是通过接口中方法的实现,使特定值能够采用多种形式。这被简单地称为多态性。综上所述,go 中的接口在其方法被调用时隐式实现,并且接口促成了多态性的概念。

fmt 包的示例代码:

1. 打印功能

Go
// Go code to visualise the differences
// between various print functions in fmt
  
package main
  
import "fmt"
  
func main() {
  
    // NOTE:
    // 1. Print(arg) prints arg as
    // it is on the console screen
    fmt.Print("Hello, welcome!")
    // OUTPUT: "Hello, welcome!"
      
    // Some variables to use in our code
    const x, id = "Ashika", 22
      
    // 2. Printf(arg) first formats arg
    // and then prints on the console screen
    fmt.Printf("\n1. Name %q and ID %d found!\n", x, id)
    // OUTPUT:
    // 1. Name "Ashika" and ID 22 found!
      
    // 3. Println(arg) does not format arg
    // It simply prints arg, appends any values
    // mentioned after arg and appends spaces in
    // between and also appends a new line at the end
    fmt.Println("2. Name %q and ID %d found!", x, id)
    // OUTPUT: 2. Name %q and ID %d found! Ashika 22
      
    // Print(arg) does not format, does not add
    // any spaces and does not append any newlines
    fmt.Print("3. Name %q and ID %d found!", x, id)
    // OUTPUT: 3. Name %q and ID %d found!Ashika22
      
    // 4. Sprint(arg) works similar to Print(arg)
    // The key difference is: Sprint returns arg as
    // it is as mentioned in the paranthesis and
    // Print(arg) prints on console screen.
    res := fmt.Sprint("\n4. Name %q and ID %d found!", x, id)
    fmt.Println(res)
    // OUTPUT:
    // 4. Name %q and ID %d found!Ashika22
      
    // 5. Sprintf(arg) works similar to Printf(arg)
    // The key difference is: Sprintf returns arg as
    // a formatted string as mentioned in the paranthesis
    // and Printf prints formatted arg on console screen
    res = fmt.Sprintf("5. Name %q and ID %d found!", x, id)
    fmt.Println(res)
    // OUTPUT: 5. Name "Ashika" and ID 22 found!
      
    // 6. Sprintln(arg) works similar to Println(arg)
    // The key difference is: Sprintln returns arg as
    // it is as mentioned in paranthesis and adds spaces
    // between variables and appends a newline to arg &
    // returns arg value while Println directly prints arg
    // onto the console screen.
    res = fmt.Sprintln("6. Name %q and ID %d found!", x, id)
    fmt.Print(res)
    // OUTPUT: 6. Name %q and ID %d found! Ashika 22
      
    fmt.Print("Goodbye!")
    // OUTPUT: "Goodbye!"
}


Go
// Go code to demonstrate use & differences
// between various scan functions in fmt package
  
package main
  
import "fmt"
  
// Main function
func main() {
  
    fmt.Print("Hello, welcome!\n")
    var y, z, age int
    var name string
      
    // Scan function will collect input
    // until a space is encountered
    // from console and stores it in y
    fmt.Scan(&y)
    fmt.Printf("Scan: Y = %d\n", y)
      
    // Scanf collects user input in
    // the specified format and stores it
    // in name and age respectively
    fmt.Scanf("%s", &name)
    fmt.Scanf("%d", &age)
    fmt.Printf("Scanf: Name = %s , Age = %d\n", name, age)
      
    // Scanln will not do nothing if
    // a newline is encountered else
    // it stores input value in z
    fmt.Scanln(&z)
    // In our case after entering age we press
    // enter so this Scanln gets skipped and
    // thus 0 is stored in z as 0 is the
    // default value of int variable in Go
    fmt.Printf("Scanln: Z = %d\n", z)
  
    var a string
    var g int
      
    // GFG is stored in a
    // 10 is stored in g
    // In case of any error, error message
    // is stored in err1
    // Number of values encountered is stored in res1
    res1, err1 := fmt.Sscan("GFG 10", &a, &g)
    // In case of any error, this block will execute
    if err1 != nil {
        panic(err1)
    }
    fmt.Printf("Sscan -> n = %d , string = %s %d \n", res1, a, g)
      
    // GFG is stored in a
    // 5 is stored in g
    // In case of any error, error message
    // is stored in err2
    // Number of values encountered is stored in res2
    res2, err2 := fmt.Sscanf("String is GFG with 5 iterations", 
                    "String is %s with %d iterations", &a, &g)
    // In case of any error, this block will execute
    if err2 != nil {
        panic(err2)
    }
    fmt.Printf("Sscanf -> n = %d , string = %s %d \n", res2, a, g)
      
    // GFG is stored in a
    // 17 is stored in g
    // In case a newline is encountered,
    // then Sscanln will raise a newline
    // panic error message
    // In case of any error, error message
    // is stored in err3
    // Number of values encountered is stored in res3
    res3, err3 := fmt.Sscanln("GFG 17", &a, &g)
    // In case of any error, this block will execute
    if err3 != nil {
        panic(err3)
    }
    fmt.Printf("Sscanln -> n = %d , string = %s %d \n", res3, a, g)
  
    fmt.Println("Goodbye!")
}


Go
// Go code to demonstrate
// the use of errorf function
// in fmt package
package main
  
import "fmt"
  
// Main function
func main() {
    const lazy = "I'm very lazy today"
      
    // Errorf formats according to the format specifier and
    // returns the string as a value that satisfies the error
    // and this error string are stored in err
    err := fmt.Errorf("Throwing error because: %q", lazy)
  
    // err.Error() will return the error message
    // and Println will print it on the output console
    fmt.Println(err.Error())
}


输出:

Hello, welcome!
1. Name "Ashika" and ID 22 found!
2. Name %q and ID %d found! Ashika 22
3. Name %q and ID %d found!Ashika22
4. Name %q and ID %d found!Ashika22
5. Name "Ashika" and ID 22 found!
6. Name %q and ID %d found! Ashika 22
Goodbye!

2. 扫描功能

// Go code to demonstrate use & differences
// between various scan functions in fmt package
  
package main
  
import "fmt"
  
// Main function
func main() {
  
    fmt.Print("Hello, welcome!\n")
    var y, z, age int
    var name string
      
    // Scan function will collect input
    // until a space is encountered
    // from console and stores it in y
    fmt.Scan(&y)
    fmt.Printf("Scan: Y = %d\n", y)
      
    // Scanf collects user input in
    // the specified format and stores it
    // in name and age respectively
    fmt.Scanf("%s", &name)
    fmt.Scanf("%d", &age)
    fmt.Printf("Scanf: Name = %s , Age = %d\n", name, age)
      
    // Scanln will not do nothing if
    // a newline is encountered else
    // it stores input value in z
    fmt.Scanln(&z)
    // In our case after entering age we press
    // enter so this Scanln gets skipped and
    // thus 0 is stored in z as 0 is the
    // default value of int variable in Go
    fmt.Printf("Scanln: Z = %d\n", z)
  
    var a string
    var g int
      
    // GFG is stored in a
    // 10 is stored in g
    // In case of any error, error message
    // is stored in err1
    // Number of values encountered is stored in res1
    res1, err1 := fmt.Sscan("GFG 10", &a, &g)
    // In case of any error, this block will execute
    if err1 != nil {
        panic(err1)
    }
    fmt.Printf("Sscan -> n = %d , string = %s %d \n", res1, a, g)
      
    // GFG is stored in a
    // 5 is stored in g
    // In case of any error, error message
    // is stored in err2
    // Number of values encountered is stored in res2
    res2, err2 := fmt.Sscanf("String is GFG with 5 iterations", 
                    "String is %s with %d iterations", &a, &g)
    // In case of any error, this block will execute
    if err2 != nil {
        panic(err2)
    }
    fmt.Printf("Sscanf -> n = %d , string = %s %d \n", res2, a, g)
      
    // GFG is stored in a
    // 17 is stored in g
    // In case a newline is encountered,
    // then Sscanln will raise a newline
    // panic error message
    // In case of any error, error message
    // is stored in err3
    // Number of values encountered is stored in res3
    res3, err3 := fmt.Sscanln("GFG 17", &a, &g)
    // In case of any error, this block will execute
    if err3 != nil {
        panic(err3)
    }
    fmt.Printf("Sscanln -> n = %d , string = %s %d \n", res3, a, g)
  
    fmt.Println("Goodbye!")
}

输入:

10
Ashika
20

输出:

Hello, welcome!
Scan: Y = 10
Scanf: Name = Ashika , Age = 20
Scanln: Z = 0
Sscan -> n =2 , string = GFG 10
Sscanf -> n = 2 , string = GFG 5
Sscanln -> n = 2 , string = GFG 17
Goodbye!

3.errorf函数演示

// Go code to demonstrate
// the use of errorf function
// in fmt package
package main
  
import "fmt"
  
// Main function
func main() {
    const lazy = "I'm very lazy today"
      
    // Errorf formats according to the format specifier and
    // returns the string as a value that satisfies the error
    // and this error string are stored in err
    err := fmt.Errorf("Throwing error because: %q", lazy)
  
    // err.Error() will return the error message
    // and Println will print it on the output console
    fmt.Println(err.Error())
}

输出:

Throwing error because: "I'm very lazy today"

Visual Studio Code 上示例代码的可视化输出:

打印函数示例代码的输出

注意: scanln 值显示为 0 作为输出。之所以如此,是因为 scanln 甚至可以收集用户输入,之前输入的换行符迫使 scanln 停止收集用户的输入。 Go 中 int 的默认值是 0,因此 Z 的值是 0。

扫描函数示例代码的输出

errorf函数示例代码的输出