Related Articles

Related Articles

Compare Println vs Printf in Golang with Examples
  • Last Updated : 10 May, 2020

Println and Printf are the functions to print the output in Golang. Both are present inside the package “fmt“. However, both these functions provide output differently as follows:

Println

Means “Print Line”. It helps us to print integers, strings, etc but inserts a new line at the end i.e. a line break is inserted. It formats the string using the default formats for its operands. Println also inserts spaces between arguments.

Syntax:

func Println(a ...interface{}) (n int, err error)

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Golang program to show the uses of Println function
package main
  
import "fmt"
  
func main() {
  
    // The Println prints and
    // adds a new line
    s := "Sam"
    age := 25
    fmt.Println("His name is", s)
  
    fmt.Println("His age is", age, "years")
}

chevron_right


Output:



His name is Sam
His age is 25 years

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Golang program to show the uses of Println function
package main
  
import "fmt"
  
func main() {
    a, b := 10, 20
  
    fmt.Println("a * b: ")
    fmt.Println(a, "*", b, "=", a*b)
}

chevron_right


Output:

a * b: 
10 * 20 = 200

Printf

Means “Print Formatter”. It prints formatted strings. It contains symbols in the string which you want to print and then arguments after it will replace those symbol points. It does not insert a new line at the end like Println. For that, you’ll have to add “\n” in the end. It formats the string according to a format specifier.

Syntax:

func Printf(format string, a ...interface{}) (n int, err error)

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Golang program to show the uses of Printf function
package main
  
import "fmt"
  
func main() {
  
    // The Printf prints but
    // doesn't add a new line
    s := "Sam"
    age := 25
  
    fmt.Printf("His name is %s", s)
  
    fmt.Printf("His age is %d ", age)
    fmt.Printf("years")
}

chevron_right


Output:

His name is SamHis age is 25 years

To be more clear, see the below example. Here Printf formats according to a specified format specifier but Println uses the default formats for its operands.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Golang program to show the uses
// of Printf and Println function
package main
  
import "fmt"
  
func main() {
    m, n, p := 15, 25, 40
  
    fmt.Println(
        "(m + n = p) :", m, "+", n, "=", p,
    )
  
    fmt.Printf(
        "(m + n = p) : %d + %d = %d\n", m, n, p,
    )
}

chevron_right


Output:

(m + n = p) : 15 + 25 = 40
(m + n = p) : 15 + 25 = 40



My Personal Notes arrow_drop_up
Recommended Articles
Page :