Go Output Functions
You can output text in Go with any of three functions:
Print()Println()Printf()
The Print() Function
Print() outputs its arguments using their default format.
Note: To start a new line, use \n.
When neither of two arguments is a string, Print() puts a space between them.
Example
Here, i and j are printed one after the other, with nothing between them:
Output: Go program and captured output
package main
import ("fmt")
func main() {
var i,j string = "Hello","World"
fmt.Print(i)
fmt.Print(j)
}
Example
To put each argument on its own line, add \n after it:
Output: Go program and captured output
package main
import ("fmt")
func main() {
var i,j string = "Hello","World"
fmt.Print(i, "\n")
fmt.Print(j, "\n")
}
Example
One Print() call can handle several variables at once:
Output: Go program and captured output
package main
import ("fmt")
func main() {
var i,j string = "Hello","World"
fmt.Print(i, "\n",j)
}
Example
Strings get no automatic space between them, so you have to add one yourself with " ":
Output: Go program and captured output
package main
import ("fmt")
func main() {
var i,j string = "Hello","World"
fmt.Print(i, " ", j)
}
Example
With integer arguments there are no strings involved, so Print() adds the space by itself:
Output: Go program and captured output
package main
import ("fmt")
func main() {
var i,j = 10,20
fmt.Print(i,j)
}
The Println() Function
Println() works much like Print(), with two additions: it always puts whitespace between its arguments, and it ends the output with a newline:
Example
Output: Go program and captured output
package main
import ("fmt")
func main() {
var i,j string = "Hello","World"
fmt.Println(i,j)
}
The Printf() Function
Printf() formats its arguments according to the formatting verb you give it, and only then prints them.
This example uses two of those verbs:
%vprints an argument's value%Tprints an argument's type
Example
Output: Go program and captured output
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)
}