Go 学习之路:Println 与 Printf 的区别

本贴最后更新于 1705 天前,其中的信息可能已经时移俗易

Println 和 Printf 都是 fmt 包中公共方法;在需要打印信息时常用的函数,那么二函数有什么区别呢?

附上代码
package main

import (
	"time"
	"fmt"
)

const (
	Man = 1
	Female = 2
)

func main(){
	timer := time.Now().Unix()
	if(timer % Female == 0){
		fmt.Println("%d is Female", timer)
		fmt.Printf("%d is Female", timer)
	}else{
		fmt.Println("%d is Man", timer)
		fmt.Printf("%d is Man", timer)
	}
}


运行结果
%d is Man 1529049077 // println输出结果
1529049077 is Man // printf输出结果
结果可知

Printf : 可打印出格式化的字符串,Println 不行;

稍做修改下
package main

import "fmt"

const (
	StrN = "123"
	IntN = 123
)

func main(){
	fmt.Println(StrN)
	fmt.Printf("%s\n",StrN)
	fmt.Printf(StrN)
	fmt.Println(IntN)
	fmt.Printf("%d\n",IntN)
	fmt.Printf(IntN)
}
结果
cannot use IntN(type int) as type string in argument to fmt.Printf

原因

// 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.
// It returns the number of bytes written and any write error encountered.
func Println(a ...interface{}) (n int, err error) {
	return Fprintln(os.Stdout, a...)
}


// Printf formats according to a format specifier and writes to standard output.
// It returns the number of bytes written and any write error encountered.
func Printf(format string, a ...interface{}) (n int, err error) {
	return Fprintf(os.Stdout, format, a...)
}

总结一句话: println 会根据你输入格式原样输出,printf 需要格式化输出并带输出格式;

  • golang

    Go 语言是 Google 推出的一种全新的编程语言,可以在不损失应用程序性能的情况下降低代码的复杂性。谷歌首席软件工程师罗布派克(Rob Pike)说:我们之所以开发 Go,是因为过去 10 多年间软件开发的难度令人沮丧。Go 是谷歌 2009 发布的第二款编程语言。

    492 引用 • 1383 回帖 • 375 关注
  • fmt
    1 引用
  • Println
    1 引用
  • Printf
    2 引用

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...