Println vs Printf vs Print in Go

  • Printf - "Print Formatter" this function allows you to format numbers, variables and strings into the first string parameter you give it
  • Print - "Print" This cannot format anything, it simply takes a string and print it
  • Println - "Print Line" same thing as Print() however it will append a newline character \n at the end.

Just as Nate said: fmt.Print and fmt.Println print the raw string (fmt.Println appends a newline)

fmt.Printf will not print a new line, you will have to add that to the end yourself with \n.

The way fmt.Printf works is simple, you supply a string that contains certain symbols, and the other arguments replace those symbols. For example:

fmt.Printf("%s is cool", "Bob") 

In this case, %s represents a string. In your case, %T prints the type of a variable.


To answer your question,

fmt.Print with \n and " " is like fmt.Println.

fmt.Printf with \n and %v is like fmt.Println.

as shown in this example:

package main

import "fmt"

func main() {
    const name, age = "Kim", 22
    //
    fmt.Print(name, " is ", age, " years old.\n")  // Kim is 22 years old.
    fmt.Printf("%v is %v years old.\n", name, age) // Kim is 22 years old.
    fmt.Println(name, "is", age, "years old.")     // Kim is 22 years old.
    //
    print(name, " is ", age, " years old.\n") // Kim is 22 years old.
    println(name, "is", age, "years old.")    // Kim is 22 years old.
}

print and println are like fmt.Print and fmt.Println with qualification. See https://stackoverflow.com/a/48420811/12817546 and https://stackoverflow.com/a/14680544/12817546.

Go offers many other ways to format I/O. See https://golang.org/pkg/fmt.

Tags:

Go