Use io.Closer and io.Seeker
Use io.Closer and io.Seeker
io.Closer defines Close() error; use it to release a resource when its contract requires closing. io.Seeker defines Seek(offset int64, whence int) (int64, error) for streams that support repositioning. Not every Reader supports seeking or closing. Check the concrete type or ask for the appropriate interface.
package main
import ( "fmt" "io" "strings")
func main() { r := strings.NewReader("abcdef") pos, err := r.Seek(2, io.SeekStart) fmt.Println(pos, err == nil) p := make([]byte, 2) n, err := io.ReadFull(r, p) fmt.Println(string(p[:n]), err == nil)}SeekStart measures from the start; SeekCurrent uses the current position; SeekEnd uses the end. Seek returns the new absolute offset and an error. Check the error before reading at the intended position. Offsets here count bytes.
Expected output:
2 truecd truePreserve close errors
package main
import ( "errors" "fmt" "io")
type resource struct{}
func (resource) Close() error { return errors.New("close failed") }func finish(c io.Closer, workErr error) error { return errors.Join(workErr, c.Close()) }func main() { r := resource{} err := finish(r, errors.New("work failed")) fmt.Println(err)}The synthetic resource fails on Close. errors.Join (Go 1.20+) preserves both failures. For a real resource, establish who owns it and whether repeated Close calls are permitted. Do not assume an arbitrary Close is idempotent. io.NopCloser wraps a Reader with a Close that does nothing, not a real cleanup operation.
Expected output:
work failedclose failedTry it locally
Seek two bytes before the end of "hello" and read the remaining bytes with io.ReadAll. Check both errors and print position and text.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
I/O contracts 03: Use io.Closer and io.Seeker
Check the lesson objective before moving on.
Which whence value measures from the end?
Should all Close implementations be assumed safe to call twice?