Skip to content

proposal: io/fs: add fs.Files() iterator #68983

@myaaaaaaaaa

Description

@myaaaaaaaaa

Proposal Details

A previous proposal for walking through directory trees can be found here:

This proposal aims for a simpler interface, making a deliberate decision to focus on the use case of reading file contents.

Signature

package fs

func Files(fsys FS, err *error) iter.Seq2[string, File]

Usage

func main() {
	var err error
	for pathName, file := range fs.Files(os.DirFS("."), &err) {
		if !strings.HasSuffix(pathName, ".json") {
			// `file` is automatically opened on the first call to Read(),
			// so skipping here doesn't waste any syscalls/network traffic.
			continue
		}

		// errors are automatically collected at the end
		json, _ := io.ReadAll(file)
		fmt.Println(json)

		// `file` is automatically closed after each iteration
	}

	// loop automatically terminates early if any error occurs,
	// including in `file` operations.
	if err != nil {
		fmt.Println(err)
	}
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions