The TempDir Function
Let’s learn about the TempDir function.
We'll cover the following
The TempDir()
method works with both testing and benchmarking. Its purpose is to create a temporary directory that is going to be used during testing or benchmarking. Go automatically removes that temporary directory when the test and its subtests or the benchmarks are about to finish with the help of the CleanUp()
method—this is arranged by Go and we do not need to use and implement CleanUp()
on our own. The exact place where the temporary directory is going to be created depends on the operating system used. On macOS, it is under /var/folders
whereas on Linux it is under /tmp
. We are going to illustrate TempDir()
in the next section where we also talk about Cleanup()
.
The Cleanup()
function
Although we present the Cleanup()
method in a testing scenario, Cleanup()
works for both testing and benchmarking. Its name reveals its purpose, which is to clean up some things that we have created when testing or benchmarking a package. However, it is we who need to tell Cleanup()
what to do—the parameter of Cleanup()
is a function that does the cleaning up. That function is usually implemented inline as an anonymous function, but we can also create it elsewhere and call it by its name.
Coding example
The cleanup.go
file contains a dummy function named Foo()
—because it contains no code, there is no point in presenting it. On the other hand, all important code can be found in cleanup_test.go
:
Get hands-on with 1200+ tech skills courses.