Introduction
In the realm of Go programming, outputting text is a fundamental task, whether it's displaying information to the user, logging messages, or debugging code. Go provides three essential functions for outputting text: Print()
, Println()
, and Printf()
. In this article, we'll explore these functions, understand their differences, and learn how to use them effectively.
The Print() Function
The Print()
function prints its arguments with their default format. It does not append a newline character at the end of the output.
package main
import "fmt"
func main() {
var i, j string = "Hello", "World"
fmt.Print(i)
fmt.Print(j)
}
Output:
HelloWorld
To print arguments in new lines, \n
can be used:
package main
import "fmt"
func main() {
var i, j string = "Hello", "World"
fmt.Print(i, "\n")
fmt.Print(j, "\n")
}
Output:
Hello
World
The Println() Function
The Println()
function is similar to Print()
, but it adds a whitespace between the arguments and a newline character at the end.
package main
import "fmt"
func main() {
var i, j string = "Hello", "World"
fmt.Println(i, j)
}
Output:
Hello World
The Printf() Function
The Printf()
function formats its arguments based on the given formatting verb and then prints them.
package main
import "fmt"
func main() {
var i string = "Hello"
var j int = 15
fmt.Printf("i has value: %v and type: %T\n", i, i)
fmt.Printf("j has value: %v and type: %T", j, j)
}
Output:
i has value: Hello and type: string
j has value: 15 and type: int
Conclusion
Output functions in Go provide versatile ways to display text, whether it's simple values, formatted output, or multi-line strings. By understanding the differences between Print()
, Println()
, and Printf()
, you can choose the appropriate function based on your requirements. Whether you're printing values for user interaction, debugging code, or logging messages, Go's output functions offer efficient and effective ways to communicate information. Happy coding!