Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 418
Aroka Avatar asked Jul 20 '26 20:07

Aroka


2 Answers

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.

like image 112
Wojtek Surowka Avatar answered Jul 23 '26 05:07

Wojtek Surowka


There is io_lib:format/2, that does the job, but note that it returns a possibly nested list of chars, not a string. For a proper string, you have to flatten/1 it afterwards:

lists:flatten(io_lib:format("~p is bigger than ~p", [6, 4]))
like image 29
radrow Avatar answered Jul 23 '26 05:07

radrow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!