fmt.Fprintf()格式化的字符串并指定写入
fmt.Fprintf()语法
func Fprintf(w io.Writer, format string, a ...any) (n int, err error)
go源码对fmt.Fprintf()方法的介绍
Fprintf formats according to a format specifier and writes to w. It returns the number of bytes written and any write error encountered.
golang标准库fmt的Fprintf()方法,将根据上述语法中format参数,生成格式化的字符串,并写入参数w指定的对象中。
fmt.Fprintf()参数
参数 | 描述 |
---|---|
w | 实现了io.Writer接口的对象,用于写入被输出的对象,常见的值包括标准输出 os.Stdout和文件 os.File等等 |
format | string类型值,即格式化的字符串,包含格式化符号,比如%d 表示整数,%s 表示字符串 |
a | 参数的个数和值与format中的格式化符号一一对应 |
fmt.Fprintf()方法返回值
写入到w参数指定的对象中的字节数n int,以及遇到的任何错误err error。
fmt.Fprintf()方法实例代码
package main
import (
"fmt"
"os"
)
func main() {
name := "玫瑰"
category := "花卉"
fmt.Fprintf(os.Stdout, "这个叫 %s,属于 %s.\n", name, category)
}
运行go文件,得到输出:
这个叫 玫瑰,属于 花卉.
免责声明:内容仅供参考。