golang中的print系函数详解
pirnt系函数来自fmt包,主要用于做各种格式的输出
这些函数主要有
- fmt.Fprintf
- fmt.Printf
- fmt.Sprintf
- fmt.Fprint
- fmt.Print
- fmt.Sprint
- fmt.Fprintln
- fmt.Println
- fmt.Sprintln
- 总结
下面来逐个分析
import (
"fmt"
"os"
"io"
)
fmt.Fprintf
- 函数原型:
Fprintf(w io.Writer, format string, a ...interface{
}) (n int, err error)
-
官方注释
Fprintf formats according to a format specifier and writes to w.It returns the number of bytes written and any write error encountered. -
Arguement
fmt.Fprintf()
依据指定的格式向第一个参数内写入字符串,第一参数必须实现了io.Writer
接口。Fprintf()
能够写入任何类型,只要其实现了Write
方法,包括os.Stdout
,文件(例如os.File
),管道,网络连接,通道等等,同样的也可以使用bufio
包中缓冲写入。bufio 包中定义了type Writer struct{...}
。Fprintf
:来格式化并输出到 io.Writers 而不是 os.Stdout。
// example
func ExampleFprintf() {
const name, age = "Kim", 22
n, err := fmt.Fprintf(os.Stdout, "%s is %d years old.\n", name, age)
// The n and err return values from Fprintf are
// those returned by the underlying io.Writer.
if err != nil {
fmt.Fprintf(os.Stderr, "Fprintf: %v\n", err)
}
fmt.Printf("%d bytes written.\n", n)
// Output:
// Kim is 22 years old.
// 21 bytes written.
}
ExampleFprintf()
Kim is 22 years old.
21 bytes written.
fmt.Printf
- 函数原型
Printf(format string, a ...interface{
}) (n int, err error)
-
官方注释
Printf formats according to a format specifier and writes to standard output.It