Input and Output
Start with Go Input and Output
A program communicates using input and output. The fmt package prints values and can scan formatted text from standard input or another reader.
What you’ll learn
- Compare Print, Println and Printf.
- Read values using a scanner function.
- Build a self-contained input example.
Understand the idea
fmt.Print writes text without adding a newline; fmt.Println adds a newline and separates arguments. fmt.Printf formats values with verbs such as %s, %d and %.2f.
Interactive programs can use fmt.Scan(&name) to read from the terminal. For a self-contained lesson runnable in online compilers, this example uses fmt.Fscan with a strings.Reader instead, demonstrating the same basic scanning idea without waiting for keyboard input.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import (
"fmt"
"strings"
)
func main() {
input := strings.NewReader("Mira 3")
var name string
var items int
_, err := fmt.Fscan(input, &name, &items)
if err != nil {
fmt.Println("Input error:", err)
return
}
fmt.Printf("%s has %d items\n", name, items)
}
Output
Mira has 3 itemsTrace what the program does
Fscan reads two whitespace-separated values from the reader. The address operators let it store values in name and items. After checking the error, Printf inserts the values into a formatted sentence.
Avoid common mistakes
fmt.Scanwaits for terminal input, which may make an online runner appear stuck.- Prefer checking the error result whenever input may be malformed.
Try it yourself
Change the reader text to "Arun 6". Then experiment with the format string to add a heading on a separate line.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced Go Input and Output in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.