Skip to content

Basic I O

Go provides several ways to read input and write output. The most common are:

  • Output: fmt.Print, fmt.Println, fmt.Printf
  • Input: fmt.Scan, fmt.Scanln, fmt.Scanf, and bufio for full lines.

Read a name and age from the user, then print a greeting.

package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
func main() {
reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter your name: ")
name, _ := reader.ReadString('\n')
name = strings.TrimSpace(name)
fmt.Print("Enter your age: ")
ageStr, _ := reader.ReadString('\n')
age, _ := strconv.Atoi(strings.TrimSpace(ageStr))
fmt.Printf("Hello %s, you are %d years old.\n", name, age)
}
Terminal window
Enter your name: Alice
Enter your age: 30
Hello Alice, you are 30 years old.