首页 > 文章列表 > PostGolang 打印函数

PostGolang 打印函数

244 2025-04-06

PostGolang 打印函数

系列:golang

golang 中的打印函数

在 golang 中,有多个函数可用于打印文本,每个函数都服务于特定的用例。以下是最常用的打印功能的说明:

1.fmt.打印

描述:
将提供的参数打印为纯文本,而不添加换行符。它不会格式化输出。

用例:
对于不需要特定格式的简单串联文本或值。

fmt.print("hello")          // output: hello
fmt.print("world")          // output: helloworld
fmt.print(123, " golang")   // output: helloworld123 golang

2. fmt.println

描述:
将提供的参数打印为纯文本并在末尾附加换行符。

用例:
对于简单的输出,您希望在打印后自动换行。

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)

3. fmt.printf

描述:
根据指定的格式字符串格式化并打印文本。除非明确包含在格式字符串中,否则不会添加换行符。

用例:
用于动态或格式化输出(例如整数、浮点数、字符串等)。

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)

4.fmt.sprintf

描述:
像 fmt.printf 一样格式化文本,但它不是打印到控制台,而是返回格式化的字符串。

用例:
用于准备字符串供以后使用(例如,记录、构建响应)。

formatted := fmt.Sprintf("Hello, %s!", "Alice")
fmt.Println(formatted)
// Output: Hello, Alice!
来源:https://dev.to/tanishparashar/post2-golang-print-functions-2lki

本类最新

查看更多