系列:golang
golang 中的打印函数
在 golang 中,有多个函数可用于打印文本,每个函数都服务于特定的用例。以下是最常用的打印功能的说明:
1.fmt.打印
描述:
将提供的参数打印为纯文本,而不添加换行符。它不会格式化输出。
用例:
对于不需要特定格式的简单串联文本或值。
fmt.print("hello") // output: hellofmt.print("world") // output: helloworldfmt.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 := 25fmt.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%sstringfmt.printf(“%s”, “go”)%dinteger (base 10)fmt.printf(“%d”, 123)%ffloating-pointfmt.printf(“%.2f”, 3.14)%vdefault format for any valuefmt.printf(“%v”, true)%ttype of the variablefmt.printf(“%t”, name)% vstruct with field namesfmt.printf(“% v”, obj)
4.fmt.sprintf
描述:
像 fmt.printf 一样格式化文本,但它不是打印到控制台,而是返回格式化的字符串。
用例:
用于准备字符串供以后使用(例如,记录、构建响应)。
formatted := fmt.Sprintf("Hello, %s!", "Alice")fmt.Println(formatted)// Output: Hello, Alice!
登录后复制
以上就是PostGolang 打印函数的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2477197.html