From the course: Go for Developers: Practical Techniques for Effective Coding
Unlock this course with a free trial
Join today to access over 24,900 courses taught by industry experts.
Performing tasks only once - Go Tutorial
From the course: Go for Developers: Practical Techniques for Effective Coding
Performing tasks only once
- There are many times when we want to perform a task only once. For example, we might want to create a database connection only once and then use it to perform a number of queries. We can use a sync once type to do this. The use of sync once is very simple. We just need to create a variable of type sync once and then call the sync once do method with a function that we want to only run once. So let's create a new struct type builder that has a built field of type Boolean. Next, let's add a build method to the builder. This method will sleep for 10 milliseconds and then mark the built field as true. Now, let's write a test for the builder. In the test, we create a loop that runs five times. Each of these loops, we'll call the build method on the builder and then assert that the builder's built field is true. The build function can be called many times, but we only want it to run once because it takes some time to complete. As we can see from the test, every call to the build function…