The sleepy for loop in Go

Written by felixge | Published 2015/10/30
Tech Story Tags: programming | golang

TLDRvia the TL;DR App

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!


Published by HackerNoon on 2015/10/30