fmt and io

View saved

Print with fmt

Use Println for quick output and Printf for formatting verbs.

name := "Go"
fmt.Println("Hello", name)
fmt.Printf("lessons=%d\n", 18)

Scan simple input

fmt.Scan reads space-separated values from standard input.

var n int
fmt.Print("Enter a number: ")
fmt.Scan(&n)
fmt.Println("got", n)

Readers and writers

Many Go APIs speak io.Reader and io.Writer. Files and buffers implement them.

import (
	"io"
	"os"
	"strings"
)

r := strings.NewReader("hello")
io.Copy(os.Stdout, r)

I/O habits

  • Always check errors from file and network calls
  • Prefer defer file.Close() after a successful open
  • bufio helps with efficient scanning of lines
  • Avoid reading unbounded input into memory blindly

Comments

One comment per signed-in account. Comments are saved with this page’s URL.