
在 golang 中,有多个函数可用于打印文本,每个函数都服务于特定的用例。以下是最常用的打印功能的说明:
描述:
将提供的参数打印为纯文本,而不添加换行符。它不会格式化输出。
用例:
对于不需要特定格式的简单串联文本或值。
fmt.print("hello") // output: hello
fmt.print("world") // output: helloworld
fmt.print(123, " golang") // output: helloworld123 golang
描述:
将提供的参数打印为纯文本并在末尾附加换行符。
用例:
对于简单的输出,您希望在打印后自动换行。
fmt.println("hello") // output: hello (with newline)
fmt.println("world") // output: world (on a new line)
fmt.println(123, "golang") // output: 123 golang (on a new line)
描述:
根据指定的格式字符串格式化并打印文本。除非明确包含在格式字符串中,否则不会添加换行符。
用例:
用于动态或格式化输出(例如整数、浮点数、字符串等)。
name := "alice"
age := 25
fmt.printf("my name is %s and i am %d years old.", name, age)
// output: my name is alice and i am 25 years old.
| verb | description | example |
|---|---|---|
| %s | string | fmt.printf("%s", "go") |
| %d | integer (base 10) | fmt.printf("%d", 123) |
| %f | floating-point | fmt.printf("%.2f", 3.14) |
| %v | default format for any value | fmt.printf("%v", true) |
| %t | type of the variable | fmt.printf("%t", name) |
| % v | struct with field names | fmt.printf("% v", obj) |
描述:
像 fmt.printf 一样格式化文本,但它不是打印到控制台,而是返回格式化的字符串。
用例:
用于准备字符串供以后使用(例如,记录、构建响应)。
formatted := fmt.Sprintf("Hello, %s!", "Alice")
fmt.Println(formatted)
// Output: Hello, Alice!
以上就是PostGolang 打印函数的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号