打印输出
1.控制台打印
1.1 fmt.Print
直接输出字符串或变量,不换行
package main
import "fmt"
func main() {
fmt.Print("Hello")
fmt.Print("World!")
}
输出
HelloWorld!
1.2 fmt.Println
输出内容并自动换行
package main
import "fmt"
func main() {
fmt.Println("Hello")
fmt.Println("World!")
}
输出
Hello
World!
1.3 fmt.Printf
格式化输出,支持占位符
package main
import "fmt"
func main() {
name := "Bob"
age := 18
fmt.Printf("Name: %s, Age: %d\n", name, age)
}
输出
Name: Bob, Age: 18
2.格式化占位符
占位符 | 说明 |
---|---|
%v | 按变量的默认格式输出 |
%+v | 输出结构体时包含字段名 |
%#v | 输出变量的 Go 语法表示形式 |
%T | 输出变量的类型 |
%d | 整数(十进制) |
%b | 整数(二进制) |
%f | 浮点数(默认精度) |
%s | 字符串 |
%t | 布尔值 |
%p | 指针 |
package main
import "fmt"
func main() {
x := 666
fmt.Printf("十进制: %d, 二进制: %b, 类型: %T\n", x, x, x)
}
输出
十进制: 666, 二进制: 1010011010, 类型: int
3.构造字符串
3.1 fmt.Sprintf
格式化字符串后返回,不输出到控制台
package main
import "fmt"
func main() {
msg := fmt.Sprintf("Hello, %s!", "Go")
fmt.Println(msg)
}
输出
Hello, Go!
3.2 fmt.Sprint
直接拼接字符串并返回
package main
import "fmt"
func main() {
msg := fmt.Sprint("Hello", " ", "Go!")
fmt.Println(msg)
}
输出
Hello Go!
4.输出到文件或自定义目标
4.1 fmt.Fprint
将内容写入自定义目标(如文件),不换行
package main
import (
"fmt"
"os"
)
func main() {
file, _ := os.Create("output.txt")
defer file.Close()
fmt.Fprint(file, "Hello, World!")
fmt.Fprint(file, "Hello, Go!")
}
执行会在当前目录下生成 output.txt
文件,文件内容如下
$ cat output.txt
Hello, World!Hello, Go!
4.2 fmt.Fprintln
写入目标并自动换行
package main
import (
"fmt"
"os"
)
func main() {
file, _ := os.Create("output.txt")
defer file.Close()
fmt.Fprintln(file, "Hello, World!")
fmt.Fprintln(file, "Hello, Go!")
}
执行会在当前目录下生成 output.txt
文件,文件内容如下
$ cat output.txt
Hello, World!
Hello, Go!
4.3 fmt.Fprintf
格式化内容并写入目标
package main
import (
"fmt"
"os"
)
func main() {
file, _ := os.Create("output.txt")
defer file.Close()
fmt.Fprintf(file, "Name: %s, Age: %d", "Alice", 25)
}
执行会在当前目录下生成 output.txt
文件,文件内容如下
$ cat output.txt
Name: Alice, Age: 25
5.错误打印
说明
在 fmt.Errorf
中使用 %s
是因为它是一个格式化占位符,用来插入字符串值。在这段代码中,"file not found"
是一个字符串,通过 %s
插入到错误信息中
之所以使用 %s
是为了让模板字符串具有灵活性:
- 动态性:可以根据实际情况插入不同的字符串值
- 代码可读性:格式化字符串让结构清晰,便于扩展和维护
- 支持其他格式化类型:如
%d
插入整数,%f
插入浮点数等
这是 Go 标准库中创建格式化错误的常用方法
package main
import "fmt"
func main() {
err := fmt.Errorf("An error occurred: %s", "file not found")
fmt.Println(err.Error())
}
输出
An error occurred: file not found
总结
Go 提供了多种打印方式,适用于不同需求:
- 简单打印:
fmt.Print
、fmt.Println
- 格式化输出:
fmt.Printf
- 构造字符串:
fmt.Sprintf
- 写入目标:
fmt.Fprint