Go provides several print functions in the fmt
package for outputting text to the console or formatting strings. These functions are essential for displaying information and debugging in Go programs.
The fmt.Println
function prints one or more values followed by a newline character. It's the simplest way to output text in Go.
fmt.Println("Hello, World!")
name := "Alice"
age := 30
fmt.Println("Name:", name, "Age:", age)
fmt.Print
is similar to fmt.Println
, but it doesn't add a newline at the end.
fmt.Print("Hello, ")
fmt.Print("World!")
fmt.Printf
allows you to format strings using verbs. It's powerful for creating custom output formats.
name := "Bob"
age := 25
fmt.Printf("Name: %s, Age: %d\n", name, age)
%v
: Default format%s
: String%d
: Integer%f
: Float%t
: Boolean%T
: Type of the valuefmt.Sprintf
formats and returns a string without printing it. It's useful for creating formatted strings for later use.
name := "Charlie"
age := 35
formattedString := fmt.Sprintf("Name: %s, Age: %d", name, age)
fmt.Println(formattedString)
fmt.Println
for simple output and debugging.fmt.Printf
when you need precise control over formatting.fmt.Sprintf
to create formatted strings for later use or manipulation.To further enhance your understanding of Go programming, explore these related topics:
Mastering Go's print functions is crucial for effective programming and debugging. Practice using these functions in various scenarios to become proficient in outputting and formatting data in your Go programs.