Assume you're coding in golang, you can do something like:
str := fmt.Sprintf("%d is bigger than %d", 6, 4)
How about 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?
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 be a string, normally there is no need to convert it to the string by calling lists:flatten
. The result of the format function is a special case of iolist. Virtually all Erlang functions expecting a string accept iolists as arguments as well.
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]))
io_lib:format/2
returns an io_list()? The docs I'm looking at say that io_lib:format/2
returns a string (which in erlang is a list of integers).
io_lib:format("test ~p", [1]).
returns [116,101,115,116,32,"1"]
which is clearly not a string (but a nested list of ints).
io_lib:format/2
does not return a string, rather it returns a nested list of integers. A string() is defined as a flat list of integers, e.g. [1, 2, 3]
, whereas io_lib:format/2
returns something like [1, 2, [3]]
, which is an iolist if the first two integers are less than 255. Pretty confusing.
To use io_lib:format/2
with unicode characters:
50> X = io_lib:format("~s is greater than ~s", [[8364], [36]]).
** exception error: bad argument
in function io_lib:format/2
called as io_lib:format("~s is greater than ~s",[[8364],"$"])
51> X = io_lib:format("~ts is greater than ~s", [[8364], [36]]).
[[8364],
32,105,115,32,103,114,101,97,116,101,114,32,116,104,97,110,
32,"$"]
52> io:format("~s~n", [X]).
** exception error: bad argument
in function io:format/2
called as io:format("~s~n",
[[[8364],
32,105,115,32,103,114,101,97,116,101,114,32,116,
104,97,110,32,"$"]])
*** argument 1: failed to format string
53> io:format("~ts~n", [X]).
€ is greater than $
ok