Throw away matches

I apologize if this has been discussed before, and I’m sure it probably has been, but it’s very hard to search for. I’ve been putting off asking about it for a while now, though, so I’m curious about this pattern:

_ = SomeMod.some_func("some_arg")

I’ve seen this in the docs before but the most prominent example I know of is the first two lines of the first function definition in Phoenix, here. If you aren’t a fan of clicking it looks like this:

# Warm up caches
_ = Phoenix.Template.engines()
_ = Phoenix.Template.format_encoder("index.html")

The best explanation I can come up with is that it’s signalling a side-effect. Is that it?? If it is, I find that kind of really nice, although perhaps at the same time it’s warmed me up a bit to typing (in Elixir) as it took me way to long to figure that out, lol.

But really, it is that it? If not, what’s up with this?

It was probably to avoid so kind of generated warning. If i see function that is not assigned or matched to anything I would assume it has a side effect, so I would not see the need for _ =.

1 Like

If you ignore a return value you get a warning, so people just assign to _ when they are really not interested in what’s returned. And since a number of CI/CD pipelines include warnings_as_errors: true, you know.

1 Like

To focus the discussion. The warnings come from an (optional) dialyzer setting. That‘s why this approach is not present in all codebases, but just some.

8 Likes

Yeah, I often use such pattern to mark that I run that piece of code for sole purpose of side effects and I do not care about return value. So it will not be perceived as unintentional omission, but deliberate choice of ignoring returned values.

7 Likes