您现在的位置是:网站首页> 编程资料编程资料

Go Println和Printf的区别详解_Golang_

2023-05-26 385人已围观

简介 Go Println和Printf的区别详解_Golang_

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不行;

总结:

println会根据你输入格式原样输出,printf需要格式化输出并带输出格式;

补充:Go基础-Go中的Println和Print和Printf之间的区别

1、Println

在Println中进行输出时:

 package main import ( f "fmt" ) func main(){ f.Println("hello","world","hello","world") f.Println("hello","world","hello","world") }

输出:

/private/var/folders/yt/24f_qg2n6879g2fg85994jf40000gn/T/___go_build_helloworld_go #gosetup

hello world hello world

hello world hello world

Process finished with exit code 0

在同一输出函数中输出多项的时候,hello和world中是存在空格的

在不同输出函数之间会换行

2、Print

在Print中进行输出时:

 package main import f "fmt" func main(){ f.Print("hello","world","hello","world") f.Print("hello","world","hello","world") }

输出:

/private/var/folders/yt/24f_qg2n6879g2fg85994jf40000gn/T/___go_build_helloworld_go #gosetup

helloworldhelloworldhelloworldhelloworld

Process finished with exit code 0

在同一个输出函数中处处多项的时候,hello和world中不存在空格

在不同输出函数之间,不换行

3、Printf

在Printf进行输出时:

 package main import f "fmt" func main(){ a := 10 b := 20 c := "hello" f.Printf("a=%d,b=%d",a,b) f.Printf("c=%s",c) }

输出:

/private/var/folders/yt/24f_qg2n6879g2fg85994jf40000gn/T/___go_build_helloworld_go #gosetup

a=10,b=20c=hello

Process finished with exit code 0

可以对参数进行格式化输出,在不同输出函数中是不换行的。

总结:

函数

同函数输出多项

不同函数输出

Println

之间存在空格

换行

Print

不存在空格

不换行

Printf

格式化输出

不换行

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。如有错误或未考虑完全的地方,望不吝赐教。

-六神源码网