SoFunction
Updated on 2025-03-05

Detailed explanation of the difference between Go Println and Printf

Println and Printf are both public methods in the fmt package; functions commonly used when printing information is needed, so what is the difference between the two functions?

Attach the code

package main
import (
 "time"
 "fmt"
)
const (
 Man = 1
 Female = 2
)
func main(){
 timer := ().Unix()
 if(timer % Female == 0){
  ("%d is Female", timer)
  ("%d is Female", timer)
 }else{
  ("%d is Man", timer)
  ("%d is Man", timer)
 }
}

Running results:

%d is Man 1529049077 // println output result

1529049077 is Man // printf output result

The results can be seen

Printf: It can print out formatted strings, Println cannot do;

Summarize:

println will output as it is based on your input format, printf needs to format the output and have the output format;

Supplementary: Go Basics - Difference between Println and Print and Printf in Go

1、Println

When outputting in Println:

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

Output:

/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

When multiple terms are output in the same output function, there are spaces in hello and world.

Winding lines between different output functions

2、Print

When outputting in Print:

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

Output:

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

helloworldhelloworldhelloworldhelloworld

Process finished with exit code 0

When multiple terms are everywhere in the same output function, there are no spaces in hello and world

No line breaks between different output functions

3、Printf

When Printf outputs:

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

Output:

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

a=10,b=20c=hello

Process finished with exit code 0

Parameters can be formatted and output, and there is no line break in different output functions.

Summarize:

function

Multiple items output in the same function

Different function output

Println

There are spaces between

Line break

Print

No space exists

No line break

Printf

Format output

No line break

The above is personal experience. I hope you can give you a reference and I hope you can support me more. If there are any mistakes or no complete considerations, I would like to give you advice.