Go语言输出函数fmt.Print、fmt.Printf、fmt.Println的用法区别

fmt 包的介绍

fmt = format,是一种格式化输出函数汇总包,用于格式化输出

fmt.Print === 原样输出

Print formats using the default formats for its operands and writes to standard output.

原样输出:

package main

import (
	"fmt"
)

func main() {
	const name, age = "Kim", 22
	fmt.Print("%s", name, "%d", age)
}
// 输出结果 : 
// %sKim%d22

因此我们需要对上述代码进行改进, 使用 fmt.Print() 完成原样输出。

package main

import (
	"fmt"
)

func main() {
	const name, age = "Kim", 22
	fmt.Print(name, age)
}
// 输出结果 
// Kim22

fmt.Printf === 格式输出

Printf formats according to a format specifier and writes to standard output.

根据格式打印输出,Printf = Print format

使用方法:

fmt.Printf("%格式1%格式2", 变量值1, 变量2)
package main

import (
	"fmt"
)

func main() {
	const name, age = "Kim", 22
	fmt.Printf(name, age)
}
// 输出结果
// Kim%!(EXTRA int=22)

上面的程序是不当的,出现了我们意料之外的结果 ,因此对其进行修改

package main

import (
	"fmt"
)

func main() {
	const name, age = "Kim", 22
	fmt.Printf("%s%d", name, age)
}
// 输出结果 
// Kim22

常见的格式输出形式:

  1. %s — 字符串
  2. %d — 10进制数值
  3. %T — type(值)
  4. %v — 值的默认格式表示
  5. %p — 表示为十六进制,并加上前导的0x    

fmt.Println === 值 + 换行 输出

Println formats using the default formats for its operands and writes to standard output. Spaces are always added between operands and a newline is appended.

按照 值 + 空格 + 换行 输出

package main

import (
	"fmt"
)

func main() {
	const name, age = "Kim", 22
	fmt.Println(name, age)
    fmt.Print("new line")
}

// 输出结果 
// Kim 22
// Kim空格22空格 + 换行
// new line

 

posted @   ricnman  阅读(289)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示