Go语言fmt包格式化输出类型及含义

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对应格式的内容。
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值