fmt.Println() / Print() / Printf()
The fmt package is one of the most commonly used standard packages in Go, providing formatted output and I/O. fmt.Println(), fmt.Print(), and fmt.Printf() are all functions that write to standard output (stdout).
Syntax
import "fmt"
// Prints with a newline (spaces are added between arguments).
fmt.Println(value1, value2, ...)
// Prints without spaces (spaces are added between non-string adjacent arguments).
fmt.Print(value1, value2, ...)
// Prints using a format string.
fmt.Printf("format string", value1, value2, ...)
Functions
| Function | Description |
|---|---|
| fmt.Println(a ...any) | Prints the arguments separated by spaces and appends a newline at the end. |
| fmt.Print(a ...any) | Prints the arguments. Adds spaces between adjacent non-string arguments. Does not append a newline. |
| fmt.Printf(format string, a ...any) | Formats and prints the arguments according to the format string. Use '\n' to insert a newline. |
Sample Code
package main
import "fmt"
type Point struct {
X, Y int
}
func main() {
name := "Go"
version := 1.22
year := 2024
// Println: adds spaces between arguments and a newline at the end.
fmt.Println("Hello, World!")
fmt.Println(name, "version", version)
fmt.Println("Release year:", year)
fmt.Println()
// Print: no newline. Adds spaces between adjacent non-string arguments.
fmt.Print("A")
fmt.Print("B")
fmt.Print("C\n") // Add a newline manually.
fmt.Print(1, 2, 3, "\n") // Spaces are added between numbers.
fmt.Print("x", "y", "\n") // No spaces between strings.
fmt.Println()
// Printf: prints using format verbs.
fmt.Printf("Language: %s\n", name)
fmt.Printf("Version: %.2f\n", version)
fmt.Printf("Decimal: %d, Octal: %o, Hex: %x\n", 255, 255, 255)
fmt.Printf("Boolean: %t\n", true)
fmt.Printf("Pointer: %p\n", &year)
// Printing a struct
p := Point{X: 10, Y: 20}
fmt.Printf("Value: %v\n", p) // Default format
fmt.Printf("With field names: %+v\n", p) // With field names
fmt.Printf("Go syntax: %#v\n", p) // Go syntax representation
fmt.Printf("Type: %T\n", p) // Type name
}
Notes
Use fmt.Println() for debugging and simple output, and fmt.Printf() for formatting numbers and strings. For a full list of format verbs (such as %v and %d), see Format Verbs. To format a value as a string instead of printing it, use fmt.Sprintf().
If the number of format verbs and arguments do not match in fmt.Printf(), no compile error occurs — instead, the output will contain %!(EXTRA ...) or %!(MISSING ...) at runtime. Use the go vet command to detect these mistakes.
For string formatting, see fmt.Sprintf() / fmt.Fprintf(). For reading from standard input, see fmt.Scan().
If you find any errors or copyright issues, please contact us.