fmt包格式化输出详解
以下参数适用于:
fmt.Printf(format string, a …interface{})
// Printf formats according to a format specifier and writes to standard output.
// It returns the number of bytes written and any write error encountered.
func Printf(format string, a ...interface{}) (n int, err error) {
return Fprintf(os.Stdout, format, a...)
}
fmt.Sprintf(format string, a …interface{}) string (n int, err error)
// Sprintf formats according to a format specifier and returns the resulting string.
func Sprintf(format string, a ...interface{}) string {
p := newPrinter()
p.doPrintf(format, a)
s := string(p.buf)
p.free()
return s
}
func 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.
func Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) {
p := newPrinter()
p.doPrintf(format, a)
n, err = w.Write(p.buf)
p.free()
return
}
fmt.Errorf(format string, a …interface{}) error
// Errorf formats according to a format specifier and returns the string
// as a value that satisfies error.
func Errorf(format string, a ...interface{}) error {
return errors.New(Sprintf(format, a...))
}
几种输出的区别:
//Fprintf 将参数列表 a 填写到格式字符串 format 的占位符中
// 并将填写后的结果写入 w 中,返回写入的字节数
func Fprintf(w io.Writer, format string, a …interface{}) (n int, err error)
// Printf 将参数列表 a 填写到格式字符串 format 的占位符中
// 并将填写后的结果写入 os.Stdout 中,返回写入的字节数
func Printf(format string, a …interface{}) (n int, err error)
// Sprintf 将参数列表 a 填写到格式字符串 format 的占位符中
// 返回填写后的结果
func Sprintf(format string, a …interface{}) string
// Errorf 将参数列表 a 填写到格式字符串 format 的占位符中
// 并将填写后的结果转换为 error 类型返回
func Errorf(format string, a …interface{}) error
测试代码
输出结果
标红的是Sprintf()方法返回的内容、%v对应格式的内容。