Start Coding

Topics

Go Print Functions

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.

Basic Print Functions

fmt.Println

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

fmt.Print is similar to fmt.Println, but it doesn't add a newline at the end.


fmt.Print("Hello, ")
fmt.Print("World!")
    

Formatted Print Functions

fmt.Printf

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)
    

Common Format Verbs

  • %v: Default format
  • %s: String
  • %d: Integer
  • %f: Float
  • %t: Boolean
  • %T: Type of the value

String Formatting

fmt.Sprintf

fmt.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)
    

Best Practices

  • Use fmt.Println for simple output and debugging.
  • Prefer fmt.Printf when you need precise control over formatting.
  • Utilize fmt.Sprintf to create formatted strings for later use or manipulation.
  • Be mindful of performance when using formatted print functions in tight loops.

Related Concepts

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.