In Go, there are several functions and methods available for displaying output to the console or other output streams. Here are the commonly used ones:
fmt.Print()
: This function is used to print text to the standard output without appending a newline character at the end.
package main
import "fmt"
func main() {
fmt.Print("Hello, ")
fmt.Print("World!")
}
Output:
Hello, World!
fmt.Println()
: This function is used to print text to the standard output and appends a newline character at the end.
package main
import "fmt"
func main() {
fmt.Println("Hello,")
fmt.Println("World!")
}
Output:
Hello,
World!
fmt.Printf()
: This function is used for formatted printing. It allows you to specify a format string with placeholders and corresponding values.
package main
import "fmt"
func main() {
name := "John"
age := 30
fmt.Printf("Name: %s, Age: %d\n", name, age)
}
Output:
Name: John, Age: 30
fmt.Sprintf()
: This function works similarly tofmt.Printf()
, but instead of printing to the standard output, it returns the formatted string.
package main
import "fmt"
func main() {
name := "John"
age := 30
message := fmt.Sprintf("Name: %s, Age: %d", name, age)
fmt.Println(message)
}
Output:
Name: John, Age: 30
These are just a few examples of output functions in Go. The fmt
package provides many more formatting options and functions for various data types. You can explore the package documentation for more details on formatting and output options.