Printing Basics
Introduction to Printing in Go
In Go programming, printing is a fundamental operation for displaying output to the console or standard output. The language provides several methods to print values, making it easy for developers to debug, log, and display information.
Standard Output Functions
Go offers multiple functions for printing in the fmt
package:
1. fmt.Println()
The most straightforward printing method that prints values with automatic line breaks.
package main
import "fmt"
func main() {
name := "LabEx"
age := 5
fmt.Println("Name:", name)
fmt.Println("Age:", age)
}
2. fmt.Print()
Prints values without automatic line breaks.
package main
import "fmt"
func main() {
fmt.Print("Hello ")
fmt.Print("World")
}
Printing Multiple Values
You can print multiple values in a single statement:
package main
import "fmt"
func main() {
x, y := 10, 20
fmt.Println("x =", x, "y =", y)
}
Printing Types of Values
Go allows printing different types of values seamlessly:
graph LR
A[Integers] --> B[Floats]
B --> C[Strings]
C --> D[Booleans]
D --> E[Structs]
package main
import "fmt"
func main() {
intValue := 42
floatValue := 3.14
stringValue := "LabEx"
boolValue := true
fmt.Println(intValue, floatValue, stringValue, boolValue)
}
Function |
Performance |
Use Case |
fmt.Println() |
Slower |
Debugging, Logging |
fmt.Print() |
Moderate |
Simple Output |
fmt.Printf() |
Fastest |
Formatted Output |
Best Practices
- Use
fmt.Println()
for simple debugging
- Choose
fmt.Printf()
for complex formatting
- Avoid excessive printing in production code
By mastering these printing techniques, you'll be able to effectively display and debug your Go programs.