Member-only story

Recursion with go

Adam Szpilewicz
3 min readMar 26, 2023

A recursive algorithm is a problem-solving approach that involves breaking down a problem into smaller subproblems that can be solved in a similar manner. The algorithm then calls itself to solve each of the smaller subproblems. This process continues until a base case is reached, which is a problem that can be solved directly without recursion. The solution to each subproblem is then combined to solve the original problem.

Recursive algorithms can be used in many different domains, including computer science, mathematics, and engineering. They are often used to solve problems that can be broken down into smaller pieces, such as searching and sorting algorithms, tree traversals, and many others. Recursion can often result in more elegant and concise code, as well as better performance in some cases. However, recursive algorithms can also be more difficult to debug and understand, and may have issues with stack overflow for large input sizes.

Example in go

This is a Go program that recursively walks through a directory and prints out all the files in that directory.

In the main function, the program defines the directory to be walked using the path variable. Then, it calls the WalkDir function, passing in an empty slice of strings to hold the file paths.

If there’s an error while walking the directory, the program prints out an error message and exits with an error code.

If there are no errors, the program prints out the files in the directory using a for loop and the fmt.Println function.

The WalkDir function takes a path and a slice of strings to hold the file paths and returns the updated slice of strings and an error. It first opens the directory at the given path using os.Open, and defers the Close call to ensure that the directory is closed at the end of the function.

Next, the function reads the file info for each file in the directory using Readdir, and loops through the returned slice of FileInfo structs. If the file is a directory, the function recursively calls itself with the directory path and the current files slice. If the file is not a directory, it appends the file's full path to the files slice.

Finally, the function returns the updated files slice and any error encountered…

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Adam Szpilewicz
Adam Szpilewicz

Written by Adam Szpilewicz

Backend software engineer working with golang and python @Rivery (https://rivery.io/). I like writting and reading about code and software engineering.

No responses yet

Write a response