Welcome to our comprehensive guide on Go's fmt package, focusing on fmt.Print, fmt.Println, and fmt.Printf. These are powerful functions that help us print and format data in the Go programming language. Let's get started! š
The fmt package in Go offers functions for formatting and printing data, including strings, integers, booleans, and more. It's an essential tool in Go development.
fmt.Print is a function used to print data to the standard output. It doesn't append a newline character at the end, unlike fmt.Println.
package main
import "fmt"
func main() {
message := "Hello, World!"
fmt.Print(message)
}In the above example, we're printing a string without a newline.
š” Pro Tip: Use fmt.Print when you don't want to add a newline at the end of your output.
fmt.Println is a function used to print data to the standard output, followed by a newline character. It's a more commonly used function for printing in Go.
package main
import "fmt"
func main() {
message := "Hello, World!"
fmt.Println(message)
}In the above example, we're printing a string with a newline at the end.
š” Pro Tip: Use fmt.Println for printing data with a newline at the end.
fmt.Printf is a function used to format and print data based on a provided format string. It's a powerful tool for printing data in a specific format.
package main
import "fmt"
func main() {
name := "John Doe"
age := 25
fmt.Printf("Hello, %s! You are %d years old.\n", name, age)
}In the above example, we're formatting and printing a string and an integer using fmt.Printf.
š” Pro Tip: Use fmt.Printf for printing data in a specific format.
Now, let's test your understanding with a few questions:
Which function prints data without a newline at the end?
Which function is used to print data in a specific format?
That's it for this lesson! In the next one, we'll dive deeper into Go's fmt package, exploring more functions and features. Happy coding! š