Go Output Functions #
Go provides three primary functions to output text to the console:
Print()
Println()
Printf()
✅ The Print() Function #
The fmt.Print()
function prints its arguments with their default formatting.
Example 1: Print two string variables #
package main
import "fmt"
func main() {
var i, j string = "Hello", "World"
fmt.Print(i)
fmt.Print(j)
}
Result:
HelloWorld
Example 2: Print arguments in new lines using \n
#
package main
import "fmt"
func main() {
var i, j string = "Hello", "World"
fmt.Print(i, "\n")
fmt.Print(j, "\n")
}
Result:
Hello
World
Example 3: Print multiple variables in one Print() call #
package main
import "fmt"
func main() {
var i, j string = "Hello", "World"
fmt.Print(i, "\n", j)
}
Result:
Hello
World
Example 4: Add a space between string arguments #
package main
import "fmt"
func main() {
var i, j string = "Hello", "World"
fmt.Print(i, " ", j)
}
Result:
Hello World
Example 5: Space automatically added between non-string arguments #
package main
import "fmt"
func main() {
var i, j = 10, 20
fmt.Print(i, j)
}
Result:
10 20
✅ The Println() Function #
The fmt.Println()
function is similar to Print()
but adds a space between arguments and a newline at the end.
Example: #
package main
import "fmt"
func main() {
var i, j string = "Hello", "World"
fmt.Println(i, j)
}
Result:
Hello World
✅ The Printf() Function #
The fmt.Printf()
function formats its arguments based on formatting verbs and prints them.
Formatting Verbs Example: #
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)
}
Result:
i has value: Hello and type: string
j has value: 15 and type: int
👉 Tip: Refer to the Formatting Verbs chapter for a complete list of verbs.
🚀 With these functions, you can effectively print output to debug, log, or display results in your Go programs.