Go Output

Displaying data and messages in Go programs

📤 What is Go Output?

Go output allows you to display text, numbers, and data to the console or terminal. The fmt package provides functions like Print, Println, and Printf for different output needs.


package main

import "fmt"

func main() {
    fmt.Println("Hello, Go!")
}
                                    

Output:

Hello, Go!

Go Output Functions

📝

fmt.Print()

Prints without adding a new line

fmt.Print("Hello ")
fmt.Print("World")
📄

fmt.Println()

Prints and adds a new line

fmt.Println("Hello")
fmt.Println("World")
🎯

fmt.Printf()

Formatted printing with placeholders

name := "Alice"
fmt.Printf("Hello %s!", name)
🔢

Multiple Values

Print multiple values at once

fmt.Println("Age:", 25, "Name:", "Bob")

🔹 Basic Print Functions

The three main print functions in Go:

package main

import "fmt"

func main() {
    // Print without newline
    fmt.Print("Hello ")
    fmt.Print("World ")
    
    // Print with newline
    fmt.Println("Go!")
    fmt.Println("Programming")
    
    // Formatted print
    age := 30
    fmt.Printf("I am %d years old\n", age)
}

Output:

Hello World Go!
Programming
I am 30 years old

🔹 Printf Format Specifiers

Common format specifiers for Printf:

package main

import "fmt"

func main() {
    name := "Alice"
    age := 25
    height := 5.6
    isStudent := true
    
    fmt.Printf("Name: %s\n", name)        // String
    fmt.Printf("Age: %d\n", age)          // Integer
    fmt.Printf("Height: %.1f\n", height)  // Float
    fmt.Printf("Student: %t\n", isStudent) // Boolean
}

Output:

Name: Alice
Age: 25
Height: 5.6
Student: true

🔹 Printing Variables

Different ways to print variables:

package main

import "fmt"

func main() {
    x := 10
    y := 20
    
    // Print variables with labels
    fmt.Println("x =", x)
    fmt.Println("y =", y)
    
    // Print multiple variables
    fmt.Println("Values:", x, y)
    
    // Formatted output
    fmt.Printf("x = %d, y = %d\n", x, y)
    fmt.Printf("Sum = %d\n", x+y)
}

Output:

x = 10
y = 20
Values: 10 20
x = 10, y = 20
Sum = 30

🧠 Test Your Knowledge

Which function adds a new line after printing?