Protocol String.Chars not implemented

Hello, everyone I’m new to Elixir, I’m learning from The Pragmatic Studio Elixir course.

I’m facing an error that I don’t understand. I have this string:

request = """
GET /posts HTTP/1.1

Host: example.com

User-Agent: ExampleBrowser/1.0

Accept: */*

"""

I’m working on a module called Servy.RequestHandler which has a function called parse_request in this function I want to parse the request and return a map:


defmodule Servy.RequestHandler do
  def parse_request(request) do
    first_line =
      request
      |> String.split("\n")
      |> List.first

    [method, path, _] = first_line |> String.split(" ")

    %{method: method, path: path, body: ""}
  end
end

trying to compile this program I get the following error:


== Compilation error in file lib/servy/request_handler.ex ==
** (Protocol.UndefinedError) protocol String.Chars not implemented for %{body: "", method: "GET", path: "/posts"} of type Map
    (elixir 1.12.2) lib/string/chars.ex:3: String.Chars.impl_for!/1
    (elixir 1.12.2) lib/string/chars.ex:22: String.Chars.to_string/1
    (elixir 1.12.2) lib/io.ex:712: IO.puts/2
    (elixir 1.12.2) lib/kernel/parallel_compiler.ex:319: anonymous fn/4 in Kernel.ParallelCompiler.spawn_workers/7

I tried to read the docs and I saw some things about defining the Protocols but I don’t understand that and why we should define them, can someone please me.

I’m using:

  • Erlang/OTP 24
  • Elixir (1.12.2)

Hello and welcome,

The error is not in this code… but somewhere You try to display the result of this function, which is a map.

Maybe You tried something like IO.puts your_func()

But You need to

IO.inspect your_func()

Because You cannot display a map as You would with a String.

5 Likes

Thanks, that’s actually it.

1 Like