概述
Printf定义在fmt包中,用于格式化字符串并写到标准输出。
下面是Printf的函数原型
func Printf(format string, a ...interface{}) (n int, err error)
Printf使用自定义指定器来格式化字符串。它也不添加新行。Printf也是一个变量函数,意味着它可以有多个参数。 关于其参数列表有两个要点
-
注意,第一个参数是一个格式或模板字符串。
-
接下来是一个数量可变的参数。这个列表中的每个参数都可以是字符串、int、struct或任何东西。这就是为什么它是一个空接口
格式或模板字符串包含需要被格式化的实际字符串和一些格式化动词。这些格式化动词告诉人们在最后的字符串中如何格式化后面的参数。 所以基本上格式化字符串参数包含某些符号,这些符号被替换成尾部参数。
例如
打印一个字符串变量
-
使用**%s**符号
-
例子
name := "John"
fmt.Printf("Name is: %s\n", name)
打印一个整数
-
使用了**%d**符号
-
例子
age := 21
fmt.Printf("Age is: %d\n", age)
打印一个结构体
例如,在打印结构时有三种格式说明。
-
%v- 它将只打印数值。将不打印字段名。这是在使用Println时打印结构的默认方式。
-
%+v - 它将同时打印字段和值。
-
%#v - 它将打印结构,同时也打印字段名和值
这就是为什么
fmt.Printf("Employee is %v\n", e)
fmt.Printf("Employee is %+v\n", e)
fmt.Printf("Employee is %#v\n", e)
分别打印出以下内容
Employee is {John 21}
Employee is {Name:John Age:21}
Employee is main.employee{Name:"John", Age:21}
这是按上面的解释。
此外,请注意该函数会返回打印的字符数以及任何错误(如果发生)。与Println不同的是,它会添加一个新行。你必须明确地添加**"\n"**。
程序
以下是相同的工作程序
package main
import (
"fmt"
"log"
)
type employee struct {
Name string
Age int
}
func main() {
name := "John"
age := 21
fmt.Printf("Name is: %s\n", name)
fmt.Printf("Age is: %d\n", age)
fmt.Printf("Name: %s Age: %d\n", name, age)
e := employee{
Name: name,
Age: age,
}
fmt.Printf("Employee is %v\n", e)
fmt.Printf("Employee is %+v\n", e)
fmt.Printf("Employee is %#v\n", e)
bytesPrinted, err := fmt.Printf("Name is: %s\n", name)
if err != nil {
log.Fatalln("Error occured", err)
}
fmt.Println(bytesPrinted)
}
输出
Name is: John
Age is: 21
Name: John Age: 21
Employee is {John 21}
Employee is {Name:John Age:21}
Employee is main.employee{Name:"John", Age:21}
Name is: John
14
请注意,在下面的Printf
fmt.Printf("Name: %s Age: %d\n", name, age)
-
%s 被名字所取代。
-
%d被年龄所取代。
所以基本上格式字符串参数中的符号或动词都被后面的参数依次替换了
如果格式字符串中的格式指定符的数量与下一个变量参数的数量不一致,那么格式指定符将被原样打印。例如,在下面的代码中,我们有两个格式指定符
-
%d
-
%s
而下一个变量的参数数只有一个。因此,当我们打印它时,它将打印第二个格式指定符,并以MISSING作为警告。
package main
import "fmt"
type employee struct {
Name string
Age int
}
func main() {
name := "John"
fmt.Printf("Name is: %s %d\n", name)
}
输出
Name is: John %!d(MISSING)
另外,请查看我们的Golang高级教程系列 -Golang高级教程
The postUnderstanding Printf function in Go (Golang)appeared first onWelcome To Golang By Example.