Go io.Copy
Copy a file to an independent destination before editing it.
A simple example
io.Copy
- Start with Source file containing A
- Do this Copy to a second file
- Result Both contain A
Syntax
io.Copy(destination, source)
Run these examples in Go
Save one example at a time as main.go. Use Go 1.21 or later.
go run main.goKeep a separate copy of a receipt
A cashier gives a customer an annotated receipt and keeps the original for the daily ledger. Copy the saved receipt, add a note to the customer copy, and check what remains in the original.
package main
import (
"os"
"fmt"
"io"
"path/filepath"
)
func check(err error) {
if err != nil { panic(err) }
}
func main() {
dir, err := os.MkdirTemp("", "lesson-")
check(err)
defer os.RemoveAll(dir)
p := func(name string) string { return filepath.Join(dir, name) }
check(os.WriteFile(p("original"), []byte("paid"), 0600))
src, err := os.Open(p("original"))
check(err)
defer src.Close()
dst, err := os.Create(p("copy"))
check(err)
_, copyErr := io.Copy(dst, src)
closeErr := dst.Close()
check(copyErr)
check(closeErr)
check(os.WriteFile(p("copy"), []byte("collected"), 0600))
original, err := os.ReadFile(p("original"))
check(err)
fmt.Println(string(original))
}
paid
The original still contains only the payment status after the destination changes.
Prepare a gallery label
A curator stores a short UTF-8 caption beside an exhibit. Make a second copy for the afternoon shift. Which text does the new file contain?
Prepare a studio handover
A stage manager saves a two-word instruction for the next shift. Make a second copy for the afternoon shift. Which text does the new file contain?
What to watch for
Existing-destination and overwrite rules vary between APIs. This exercise uses a fresh destination.