fmt Go language's standard library

fmt standard library is our first contact with one of the most frequent in the Go language learning process, this article describes some common functions fmtb package.

fmt

to achieve a similar package fmt C language printf and scanf formatted I / O. Divided into output externally input content and access the contents of two parts.

Output outwardly

The standard library fmtprovides the following output related functions.

Print

PrintSUMMARY series function will output to the standard output of the system, except that the Printfunction of directly outputting content, Printffunction supports formatted output string, Printlnthe function adds the output end of a line break in the 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)

Here is a simple example:

func main() {
    fmt.Print("在终端打印该信息。")
    name := "沙河小王子"
    fmt.Printf("我是:%s\n", name)
    fmt.Println("在终端打印单独一行显示")
}

Execution code output above:

在终端打印该信息。我是:沙河小王子
在终端打印单独一行显示

Fprint

FprintSeries function will be output to a content io.Writerinterface type of variable w, we usually use this function to write the contents of the 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)

for example:

// 向标准输出写入内容
fmt.Fprintln(os.Stdout, "向标准输出写入内容")
fileObj, err := os.OpenFile("./xx.txt", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
if err != nil {
    fmt.Println("打开文件出错,err:", err)
    return
}
name := "沙河小王子"
// 向打开的文件句柄中写入内容
fmt.Fprintf(fileObj, "往文件中写如信息:%s", name)

Note that, as long as io.Writerthe type of interface will support writing.

Sprint

SprintSeries function will generate incoming data and returns a string.

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

Simple example code is as follows:

s1 := fmt.Sprint("沙河小王子")
name := "沙河小王子"
age := 18
s2 := fmt.Sprintf("name:%s,age:%d", name, age)
s3 := fmt.Sprintln("沙河小王子")
fmt.Println(s1, s2, s3)

Errorf

ErrorfThe format string format function generates and returns a string containing the error.

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

, Normally used to customize the type of error, for example:

err := fmt.Errorf("这是一个错误")

Formatting placeholder

*printfFamily of functions supported format to format parameters, where the variables we follow the placeholder will be replaced Classification, easy access and memory.

Universal placeholder

Placeholder Explanation
% v The default format representation of the value
% + V Similarly% v, but will add field names output structure
% # V Go syntax representation of the value
%T The value of the type of print
%% Percent sign

Sample code is as follows:

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

Output:

100
false
{小王子}
struct { name string }{name:"小王子"}
struct { name string }
100%

Boolean

Placeholder Explanation
%t true or false

Integer

Placeholder Explanation
%b Represented as binary
%c Unicode value corresponding to the code value
%d Expressed as a decimal
%The Expressed as octal
%x Expressed in hexadecimal, use af
%X Expressed in hexadecimal, using the AF
% U Unicode format is expressed as: U + 1234, equivalent to "U +% 04X"
%q This value corresponds to the single quotation marks go character literal syntax, will be used when safe escape necessarily represent

Sample 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)

Output:

1000001
A
65
101
41
41

Floating point and complex

Placeholder Explanation
%b No fractional part, binary exponential scientific notation, such as -123456p-78
%e Scientific notation, such as -1234.456e + 78
%E Scientific notation, such as -1234.456E + 78
%f Fractional part without exponential portion, 123.456
%F % F is equivalent to
%g The actual use of the% f% e, or (for a more concise, accurate output)
%G The actual conditions employed or% F% E format (for a more concise, accurate output)

Sample 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)

Output:

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

And String [] byte

Placeholder Explanation
%s Or directly output string [] byte
%q This value corresponds to the double quotation marks go syntax string literals, will be used when safe escape necessarily represent
%x Each byte is represented (af use with two-character hexadecimal number
%X Each byte is represented (using AF) with a two-character hexadecimal

Sample code is as follows:

s := "小王子"
fmt.Printf("%s\n", s)
fmt.Printf("%q\n", s)
fmt.Printf("%x\n", s)
fmt.Printf("%X\n", s)

Output:

小王子
"小王子"
e5b08fe78e8be5ad90
E5B08FE78E8BE5AD90

pointer

Placeholder Explanation
%p He expressed as hexadecimal, and with leading the 0x

Sample code is as follows:

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

Output:

0xc000094000
c000094000

Width identifier

Width by a percent sign immediately behind the decimal number specified, if the width is not specified, it indicates that in addition to the required value will not be filled. Accuracy by (optional) followed by a decimal point number is followed by the width specified. If the precision is not specified, it will use the default precision; if the dot is not with the number representing the precision is 0. For example as follows:

Placeholder Explanation
%f Default width, default precision
% 9f Width 9, the default precision
% .2f Default width, precision 2
% 9.2f 9 width, precision 2
%9.f 9 width, precision 0

Sample code is as follows:

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)

Output:

12.340000
12.340000
12.34
    12.34
       12

Other falg

Placeholder Explanation
’+’ Always outputs the value sign; of% q (% + q) will generate all ASCII characters is output (by escaping);
’ ‘ Numerical, the number of spaces just before the minus sign before the negative; spaces between a byte or string using% x% X (% x or% X) will each be printed
’-’ Filling gaps in the output of the right to the left instead of the default (i.e., aligned from right to switch to the default left-justified);
’#’ Plus 0 (% # o) before octal, hexadecimal front plus 0x (% # x) or 0X (% # X), remove the front pointer 0x (% # p) of% q (% # q) of% U (% # U) and outputs the spaces go single quotes literal;
‘0’ Instead of spaces filled with 0, for 0 value type will fill on the back of the sign;

for example:

s := "小王子"
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)

Output:

小王子
  小王子
小王子  
  小王子
小王子  
   小王
00小王子

Get input

Go language fmtunder-cladding fmt.Scan, fmt.Scanf, fmt.Scanlnthree functions, user input may be obtained from the standard input program is running.

fmt.Scan

Signature function given as follows:

func Scan(a ...interface{}) (n int, err error)
  • Scan从标准输入扫描文本,读取由空白符分隔的值保存到传递给本函数的参数中,换行符视为空白符。
  • 本函数返回成功扫描的数据个数和遇到的任何错误。如果读取的数据个数比提供的参数少,会返回一个错误报告原因。

具体代码示例如下:

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

将上面的代码编译后在终端执行,在终端依次输入小王子28false使用空格分隔。

$ ./scan_demo 
小王子 28 false
扫描结果 name:小王子 age:28 married:false 

fmt.Scan从标准输入中扫描用户输入的数据,将以空白符分隔的数据分别存入指定的参数。

fmt.Scanf

函数签名如下:

func Scanf(format string, a ...interface{}) (n int, err error)
  • Scanf从标准输入扫描文本,根据format参数指定的格式去读取由空白符分隔的值保存到传递给本函数的参数中。
  • 本函数返回成功扫描的数据个数和遇到的任何错误。

代码示例如下:

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

将上面的代码编译后在终端执行,在终端按照指定的格式依次输入小王子28false

$ ./scan_demo 
1:小王子 2:28 3:false
扫描结果 name:小王子 age:28 married:false 

fmt.Scanf不同于fmt.Scan简单的以空格作为输入数据的分隔符,fmt.Scanf为输入数据指定了具体的输入内容格式,只有按照格式输入数据才会被扫描并存入对应变量。

例如,我们还是按照上个示例中以空格分隔的方式输入,fmt.Scanf就不能正确扫描到输入的数据。

$ ./scan_demo 
小王子 28 false
扫描结果 name: age:0 married:false 

fmt.Scanln

函数签名如下:

func Scanln(a ...interface{}) (n int, err error)
  • Scanln类似Scan,它在遇到换行时才停止扫描。最后一个数据后面必须有换行或者到达结束位置。
  • 本函数返回成功扫描的数据个数和遇到的任何错误。

具体代码示例如下:

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

将上面的代码编译后在终端执行,在终端依次输入小王子28false使用空格分隔。

$ ./scan_demo 
小王子 28 false
扫描结果 name:小王子 age:28 married:false 

fmt.Scanln遇到回车就结束扫描了,这个比较常用。

bufio.NewReader

有时候我们想完整获取输入的内容,而输入的内容可能包含空格,这种情况下可以使用bufio包来实现。示例代码如下:

func bufioDemo() {
    reader := bufio.NewReader(os.Stdin) // 从标准输入生成读对象
    fmt.Print("请输入内容:")
    text, _ := reader.ReadString('\n') // 读到换行
    text = strings.TrimSpace(text)
    fmt.Printf("%#v\n", text)
}

Fscan系列

这几个函数功能分别类似于fmt.Scanfmt.Scanffmt.Scanln三个函数,只不过它们不是从标准输入中读取数据而是从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)

Sscan系列

这几个函数功能分别类似于fmt.Scanfmt.Scanffmt.Scanln三个函数,只不过它们不是从标准输入中读取数据而是从指定字符串中读取数据。

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)

Guess you like

Origin www.cnblogs.com/nickchen121/p/11517458.html