首页 > 其他分享 >Go语言输出函数fmt.Print、fmt.Printf、fmt.Println的用法区别

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

时间:2022-10-24 22:57:31浏览次数:62  
标签:输出 name fmt Print Println main age

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(值)

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

 

标签:输出,name,fmt,Print,Println,main,age
From: https://www.cnblogs.com/arichman/p/16823349.html

相关文章