In Go, there are three primary functions for printing output: Print()
, Println()
, and Printf()
. These functions allow you to display data and messages in the console with varying levels of formatting.
The Print()
Function
The Print()
function outputs its arguments using their default format without adding spaces or newlines.
Example:
This program demonstrates printing two strings side by side:
package main
import ("fmt")
func main() {
var yamaha, honda string = "Speed", "Thrills"
fmt.Print(yamaha)
fmt.Print(honda)
}
Result:
SpeedThrills
Example:
To print each argument on a new line, you can use \n
:
package main
import ("fmt")
func main() {
var yamaha, honda string = "Speed", "Thrills"
fmt.Print(yamaha, "\n")
fmt.Print(honda, "\n")
}
Result:
Speed
Thrills
Example:
Alternatively, one Print()
can be used to display multiple variables:
package main
import ("fmt")
func main() {
var yamaha, honda string = "Speed", "Thrills"
fmt.Print(yamaha, "\n", honda)
}
Result:
Speed
Thrills
Example:
To add a space between string arguments, include a space explicitly:
package main
import ("fmt")
func main() {
var yamaha, honda string = "Speed", "Thrills"
fmt.Print(yamaha, " ", honda)
}
Result:
Speed Thrills
Example:
If the arguments are not strings, Print()
automatically inserts a space:
package main
import ("fmt")
func main() {
var yamaha, honda = 100, 200
fmt.Print(yamaha, honda)
}
Result:
100 200
The Println()
Function
The Println()
function is similar to Print()
but automatically adds a space between its arguments and appends a newline at the end.
Example:
package main
import ("fmt")
func main() {
var yamaha, honda string = "Speed", "Thrills"
fmt.Println(yamaha, honda)
}
Result:
Speed Thrills
The Printf()
Function
The Printf()
function allows for advanced formatting of its arguments. It formats the input according to specific “verbs.”
Common Formatting Verbs:
%v
: Displays the value of the argument.%T
: Displays the type of the argument.
Example:
package main
import ("fmt")
func main() {
var yamaha string = "Speed"
var honda int = 120
fmt.Printf("yamaha has value: %v and type: %T\n", yamaha, yamaha)
fmt.Printf("honda has value: %v and type: %T", honda, honda)
}
Result:
yamaha has value: Speed and type: string
honda has value: 120 and type: int