Go Println和Printf的區(qū)別詳解
Println 和Printf 都是fmt包中公共方法;在需要打印信息時(shí)常用的函數(shù),那么二函數(shù)有什么區(qū)別呢?
附上代碼
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) } }
運(yùn)行結(jié)果:
%d is Man 1529049077 // println輸出結(jié)果
1529049077 is Man // printf輸出結(jié)果
結(jié)果可知
Printf : 可打印出格式化的字符串,Println不行;
總結(jié):
println會(huì)根據(jù)你輸入格式原樣輸出,printf需要格式化輸出并帶輸出格式;
補(bǔ)充:Go基礎(chǔ)-Go中的Println和Print和Printf之間的區(qū)別
1、Println
在Println中進(jìn)行輸出時(shí):
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
在同一輸出函數(shù)中輸出多項(xiàng)的時(shí)候,hello和world中是存在空格的
在不同輸出函數(shù)之間會(huì)換行
2、Print
在Print中進(jìn)行輸出時(shí):
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
在同一個(gè)輸出函數(shù)中處處多項(xiàng)的時(shí)候,hello和world中不存在空格
在不同輸出函數(shù)之間,不換行
3、Printf
在Printf進(jìn)行輸出時(shí):
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
可以對(duì)參數(shù)進(jìn)行格式化輸出,在不同輸出函數(shù)中是不換行的。
總結(jié):
函數(shù) |
同函數(shù)輸出多項(xiàng) |
不同函數(shù)輸出 |
Println |
之間存在空格 |
換行 |
|
不存在空格 |
不換行 |
Printf |
格式化輸出 |
不換行 |
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教。
相關(guān)文章
Go語言函數(shù)的延遲調(diào)用(Deferred Code)詳解
本文將介紹Go語言函數(shù)和方法中的延遲調(diào)用,正如名稱一樣,這部分定義不會(huì)立即執(zhí)行,一般會(huì)在函數(shù)返回前再被調(diào)用,我們通過一些示例來了解一下延遲調(diào)用的使用場(chǎng)景2022-07-07golang獲取變量或?qū)ο箢愋偷膸追N方式總結(jié)
在golang中并沒有提供內(nèi)置函數(shù)來獲取變量的類型,但是通過一定的方式也可以獲取,下面這篇文章主要給大家介紹了關(guān)于golang獲取變量或?qū)ο箢愋偷膸追N方式,需要的朋友可以參考下2022-12-12golang gopm get -g -v 無法獲取第三方庫(kù)的解決方案
這篇文章主要介紹了golang gopm get -g -v 無法獲取第三方庫(kù)的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2021-05-05Go中Gzip與json搭配實(shí)現(xiàn)數(shù)據(jù)壓縮demo
這篇文章主要為大家介紹了Go中Gzip與json搭配使用壓縮數(shù)據(jù)的實(shí)現(xiàn)demo,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-05-05Golang分布式注冊(cè)中心實(shí)現(xiàn)流程講解
這篇文章主要介紹了Golang分布式注冊(cè)中心實(shí)現(xiàn)流程,注冊(cè)中心可以用于服務(wù)發(fā)現(xiàn),服務(wù)注冊(cè),配置管理等方面,在分布式系統(tǒng)中,服務(wù)的發(fā)現(xiàn)和注冊(cè)是非常重要的組成部分,需要的朋友可以參考下2023-05-05