Golang fmt.print()函数及示例
在Golang中,我们经常需要输出一些信息来进行调试或者打印一些结果。其中,最基础也是最常用的函数就是fmt包中的print()函数。
基础用法
使用fmt包的print()函数可以输出任何基本类型,例如字符串、数字、布尔值等。下面我们来看一个简单的示例:
package main
import "fmt"
func main() {
fmt.Print("Hello, world!")
}
输出结果为:
Hello, world!
可以看到,print()函数输出的是一个字符串。如果我们想要在字符串中插入一些变量的值呢?可以使用类似于Python中的字符串格式化方法:
package main
import "fmt"
func main() {
var name string = "John"
age := 20
fmt.Printf("%s is %d years old.", name, age)
}
输出结果:
John is 20 years old.
这里的%s和%d是格式化占位符,分别对应字符串和整数类型。
如果我们想要输出多个变量或者常量,可以使用逗号分隔:
package main
import "fmt"
func main() {
var year, month, day = 2022, 5, 1
fmt.Print("The date is ", year, "/", month, "/", day)
}
输出结果为:
The date is 2022/5/1
格式化输出
使用fmt包,我们还可以进行更加复杂的格式化输出。下面是一些示例:
package main
import "fmt"
func main() {
// 使用逗号分隔参数进行格式化输出
fmt.Printf("The value of PI is approximately %f\n", 3.14159)
// 设定输出宽度、精度和占位符的类型
fmt.Printf("|%7d|%7d|\n", 1234, 5678)
// 设定输出的对齐方式(默认为右对齐)
fmt.Printf("|%-7d|%-7d|\n", 1234, 5678)
// 设定占位符的类型和字符串长度
fmt.Printf("|%6.2f|%6.2f|\n", 1.2, 3.45)
}
输出结果为:
The value of PI is approximately 3.141590
| 1234| 5678|
|1234 |5678 |
| 1.20| 3.45|
print()函数的小技巧
- 将输出重定向到文件
我们可以将print()函数的输出重定向到文件中,例如:
package main
import (
"fmt"
"os"
)
func main() {
file, _ := os.Create("output.txt")
defer file.Close()
fmt.Fprintf(file, "This is a line output to file!\n")
fmt.Fprintf(file, "This is another line output to file!\n")
}
这里使用了fmt.Fprintf()函数,它的用法与fmt.Printf()相同,只不过输出结果被重定向到了文件中。
- 取消输出换行符
我们可以使用fmt.Print()函数的变种函数fmt.Print/ln()来取消输出末尾的换行符:
package main
import "fmt"
func main() {
str := "This is a string"
fmt.Print(str)
fmt.Println()
fmt.Printf("The length of the string is %d\n", len(str))
}
输出结果为:
This is a stringThe length of the string is 16
- 输出格式化的JSON
我们可以使用fmt包的MarshalIndent()函数来格式化输出JSON格式的字符串:
package main
import (
"encoding/json"
"fmt"
)
type Person struct {
Name string
Age int
}
func main() {
p := Person{"John Smith", 20}
data, err := json.MarshalIndent(p, "", " ")
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println(string(data))
}
输出结果为:
{
"Name": "John Smith",
"Age": 20
}
可以看到,输出的JSON格式字符串已经进行了格式化对齐。
结论
在Golang中,fmt包的print()函数是非常基础也是非常重要的一个函数。通过本文的介绍,我们学习了print()函数的基础用法和格式化输出的技巧,并且了解了一些小技巧,例如重定向输出到文件和格式化输出JSON字符串。希望本文能够帮助大家更好地使用print()函数。