Go语言中的fmt.Print, fmt.Printf, fmt.Println的区别和使用场景

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

常见的格式输出形式
%s — 字符串
%d — 10进制数值
%T — type(值)

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)
}

// 输出结果 
// Kim 22
// Kim空格22空格
  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值