The fmt
package is a core component of Go's standard library. It provides essential functionality for formatted I/O operations, making it indispensable for most Go programs.
The fmt package serves two primary purposes:
It offers a wide range of functions for printing, scanning, and string manipulation, making it a versatile tool for Go developers.
fmt.Print()
: Prints arguments to standard outputfmt.Println()
: Prints arguments followed by a newlinefmt.Printf()
: Prints formatted outputfmt.Scan()
: Scans text from standard inputfmt.Scanf()
: Scans formatted text from standard input
package main
import "fmt"
func main() {
name := "Alice"
age := 30
fmt.Printf("Hello, %s! You are %d years old.\n", name, age)
}
This example demonstrates the use of fmt.Printf()
for formatted output. The %s
and %d
are format specifiers for string and integer values, respectively.
package main
import "fmt"
func main() {
var name string
var age int
fmt.Print("Enter your name and age: ")
fmt.Scan(&name, &age)
fmt.Printf("Hello, %s! You are %d years old.\n", name, age)
}
This example shows how to use fmt.Scan()
to read user input. The &
operator is used to pass pointers to the variables, allowing Scan()
to modify their values.
fmt.Println()
for simple, unformatted outputfmt.Printf()
when you need precise control over output formattingTo deepen your understanding of Go's I/O capabilities, explore these related topics:
The fmt package is a cornerstone of Go programming, essential for both beginners and experienced developers. By mastering its functions, you'll greatly enhance your ability to create robust and user-friendly Go applications.