Hackernoon logoThe sleepy for loop in Go by@felixge

The sleepy for loop in Go

Felix Geisendörfer Hacker Noon profile picture

Felix Geisendörfer

Contrived example: Let’s say you have a JSON file with an array of IP address strings, and you want to reload this file every 3 seconds, and then doSomething with every IP that’s new. And in case the file doesn’t exist, or contains invalid JSON, you want to retry in 3 seconds as well:

The code above should get the job done, but it’s a little annoying that we need to repeat the sleep statement all over the place.

So here is a pattern I’ve started to use in situations like this as of late, I’m calling it the “sleepy for loop”:

I’m probably not the first one to (ab)use the post statement of a for loop like this, but I haven’t seen this pattern used much before, so I’m sharing it in the hope it will be interesting and useful to some of you out there.

With some small modifications, it can also be used for finite loops. E.g. if we just wanted to load our IPs once, with 2 retries on error:

Anyway, even though I’m quite happy with the sleepy for loop, the same code can obviously be written without it as well. In fact my co-worker wasn’t a fan of it this morning, so we ended up settling for something like this:

I definitely prefer the sleepy for loop, but I don’t feel strongly enough about it to recommend forcing it on people who think it’s weird :).

Anyway what do you think? Please share your feedback and alternative ideas.

Hacker Noon is how hackers start their afternoons. We’re a part of the @AMIfamily. We are now accepting submissions and happy to discuss advertising & sponsorship opportunities.
To learn more, read our about page, like/message us on Facebook, or simply, tweet/DM @HackerNoon.
If you enjoyed this story, we recommend reading our latest tech stories and trending tech stories. Until next time, don’t take the realities of the world for granted!


Join Hacker Noon

Create your free account to unlock your custom reading experience.