String.at edge case

I just stumbled upon this edge case that was non-intuitive to me. Now I’m wondering if this behavior makes sense or not.

It has to do with String.at when the string is nil and position is 0:

String.at nil, 0
=> nil # Was expecting an error here, as in the next example:
String.at nil, 1
=> ** (FunctionClauseError) no function clause matching in String.Unicode.next_grapheme_size/1

I was surprised that nil was returned because all (most?) String functions will raise (some sort of) a FunctionClauseError when the input string is not a binary. Is that a wrong assumption?

3 Likes

It might fall into the case of:

If position is greater than string length, then it returns nil.

But I’m with you that it should probably error consistently.

Great find! Please send a PR or report an issue. :slight_smile:

1 Like

Issue reported: https://github.com/elixir-lang/elixir/issues/10530

But of course only after doing that I checked the latest Elixir code and I think this has been solved by this recent MR: https://github.com/elixir-lang/elixir/pull/10506/files

Great work! It also shows I should update more often. :kissing_cat: