First of all, there’s two string-like data structures in Elixir:
- charlist - a list of integers where all the integers are valid code points
- it is often used for interoperability with Erlang
- string - a UTF-8 encoded binary
- it is equivalent to strings in most other languages.
Then, there are three types of syntax:
'usa'
is the syntax for creating a charlist.~c"usa"
is the new syntax for creating a charlist."usa"
is the syntax for creating a string.
When you create a charlist the warning you mentioned will be shown. Try:
iex> 'usa'
warning: single-quoted strings represent charlists. Use ~c"" if you indeed want a charlist or use "" instead
Why is this warning shown?
Because single-quotes confuse people sometimes, so the core team encourages using ~c
for creating a charlist.
You can read Binaries, strings, and charlists — Elixir v1.17.2 for more context.
The answers of your problem:
What am I doing wrong?
You are creating a charlist with single-quotes.
Is there a better style to write this, say with pattern matching?
I can’t answer this.
Extra - The potential problems of your code:
- you are comparing a charlist with a string. (But, you shouldn’t)
- you are creating a fetch_or_insert function which has data-racing problem. Read more at How to do get_or_insert_by in Ecto without race condition?