0
0
GoHow-ToBeginner · 3 min read

How to Use fmt.Println in Go: Simple Print Output Guide

Use fmt.Println in Go to print text or variables to the console with a newline at the end. Import the fmt package, then call fmt.Println() with the values you want to display.
📐

Syntax

The basic syntax of fmt.Println is simple. You write fmt.Println() and put the values you want to print inside the parentheses, separated by commas. It automatically adds a space between values and a newline at the end.

  • fmt: The package that contains the print functions.
  • Println: The function that prints with a newline.
  • Arguments: Values to print, like strings, numbers, or variables.
go
fmt.Println(value1, value2, ...)
💻

Example

This example shows how to print a simple message and a number using fmt.Println. It demonstrates printing text and variables together.

go
package main

import "fmt"

func main() {
    name := "Alice"
    age := 30
    fmt.Println("Hello, my name is", name)
    fmt.Println("I am", age, "years old")
}
Output
Hello, my name is Alice I am 30 years old
⚠️

Common Pitfalls

Some common mistakes when using fmt.Println include forgetting to import the fmt package, missing commas between values, or expecting no spaces between printed values.

Also, fmt.Println always adds a space between arguments and a newline at the end, so if you want no spaces or no newline, use other functions like fmt.Print or fmt.Printf.

go
package main

import "fmt"

func main() {
    // Wrong: missing comma between values
    // fmt.Println("Hello" "World") // This causes a compile error

    // Right: add comma
    fmt.Println("Hello", "World")

    // Wrong: forgetting to import fmt
    // fmt.Println("Hello") // This causes an error
}
Output
Hello World
📊

Quick Reference

  • fmt.Println(): Prints values with spaces and adds a newline.
  • fmt.Print(): Prints values without adding a newline.
  • fmt.Printf(): Prints formatted strings using verbs like %s, %d.
  • Always import fmt to use these functions.

Key Takeaways

Always import the fmt package to use fmt.Println.
Use fmt.Println to print values separated by spaces with a newline at the end.
Separate multiple values with commas inside fmt.Println parentheses.
fmt.Println automatically adds spaces between values and a newline after printing.
For no newline or custom formatting, consider fmt.Print or fmt.Printf.