Go Output
Go output is the text and numbers a program prints to the screen. The fmt package gives three ways to print values.
Println ends each line
Each Println call prints one value. Each call ends its line.
package main
import "fmt"
func main() {
fmt.Println("Hello")
fmt.Println("World")
}Print joins strings with no space
Println adds a space between two strings. Print joins two strings with no space.
package main
import "fmt"
func main() {
fmt.Println("a", "b")
fmt.Print("a", "b")
}Print spaces two numbers
Neither value here is a string. Print puts a space between the two numbers.
package main
import "fmt"
func main() {
fmt.Print(1, 2)
}Printf fills in values
The pattern holds two verbs. Printf fills %s with a string and %d with a number.
package main
import "fmt"
func main() {
fmt.Printf("%s is %d", "Hana", 27)
}Printf shows a type and a value
The %T verb prints the type of a value. The %v verb prints the value itself.
package main
import "fmt"
func main() {
fmt.Printf("%T %v", "Go", "Go")
}Example
package main
import "fmt"
func main() {
fmt.Printf("%s %d\n", "Pen", 3)
fmt.Printf("%s %d", "Total", 6)
}Key points
- fmt.Println prints values and ends the line.
- fmt.Print prints values without ending the line.
- fmt.Print adds a space between two numbers.
- fmt.Println adds spaces between the values it prints.
- fmt.Printf builds a line from a pattern and values.
- Use %d for a whole number and %s for a string.
- Use %T for a type and %v for a value.
In this example, the first Printf prints Pen and the count 3. The newline ends the first line. The second Printf prints Total and the number 6.
Note
fmt.Printf adds no newline on its own.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Go Playground
Exercise
Which call prints a value and ends the line?