Search code examples
erlangstring-formatting

How to return a formatted string in Erlang?


Assume you're coding in golang, you can do something like:

str := fmt.Sprintf("%d is bigger than %d", 6, 4)

How about Erlang?


Solution

  • The Erlang equivalent would be

    Str = io_lib:format("~p is bigger than ~p", [6, 4])
    

    Note that, even if the result may be not technically a string, normally there is no need to convert it to the string by calling lists:flatten. The result of the format function usually is a special case of iolist. Virtually all Erlang functions expecting a string accept iolists as arguments as well.

    "Usually" above means "if Unicode modifier is not used in the format string". In most cases there is no need to use Unicode modifiers, and the result of format can be used directly as described above.