String Comparison Style

I have an CSV file of concerts. When parsing, I have already created the country “usa” as there are thousands of them in this file. Instead of hitting the db, I create the entry ahead of time into the var usa_country_id.

usa_country_id = fetch_or_insert_country("usa")

...

def fetch_or_insert_country(country) do
  Repo.get_by(Country, country: country) || Repo.insert!(%Country{country: country})
end

Perfect - works great. But, for some reason, I get this warning with the code when I set the country_id for a save later:

 country_id = if country == 'usa', do: usa_country_id, else: fetch_or_insert_country(country).country_id
warning: single-quoted strings represent charlists. Use ~c"" if you indeed want a 
charlist or use "" instead

What am I doing wrong? Is there a better style to write this, say with pattern matching?

Thank you

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:

3 Likes