Title here
Summary here
-module(string_formatting).
-export([main/0]).
-record(point, {x, y}).
main() ->
% Erlang offers several formatting options for strings and other data types.
% Here are some examples of common string formatting tasks.
% For basic string formatting, we can use the io:format function.
P = #point{x = 1, y = 2},
io:format("struct1: ~p~n", [P]),
% To include record field names, we can use the #-syntax
io:format("struct2: ~p~n", [P#point{x = P#point.x, y = P#point.y}]),
% There's no direct equivalent to Go's %#v, but we can use ~p for a similar effect
io:format("struct3: ~p~n", [P]),
% To print the type of a value, we can use erlang:type_of/1
io:format("type: ~p~n", [erlang:type_of(P)]),
% Formatting booleans is straightforward
io:format("bool: ~p~n", [true]),
% For integers, use ~B for base 10
io:format("int: ~B~n", [123]),
% For binary representation, use ~.2B
io:format("bin: ~.2B~n", [14]),
% To print a character, use ~c
io:format("char: ~c~n", [33]),
% For hexadecimal, use ~.16B
io:format("hex: ~.16B~n", [456]),
% For basic float formatting, use ~f
io:format("float1: ~f~n", [78.9]),
% For scientific notation, use ~e
io:format("float2: ~e~n", [123400000.0]),
io:format("float3: ~E~n", [123400000.0]),
% For basic string printing, use ~s
io:format("str1: ~s~n", ["\"string\""]),
% To include quotes, use ~p
io:format("str2: ~p~n", ["\"string\""]),
% For hexadecimal representation of a string, use ~.16B
io:format("str3: ~.16B~n", [list_to_binary("hex this")]),
% To print a pointer (reference in Erlang), use ~p
io:format("pointer: ~p~n", [make_ref()]),
% To control width, use ~B with a number
io:format("width1: |~6B|~6B|~n", [12, 345]),
% For floats with width and precision, use ~w.df
io:format("width2: |~6.2f|~6.2f|~n", [1.2, 3.45]),
% To left-justify, use - before the width
io:format("width3: |~-6.2f|~-6.2f|~n", [1.2, 3.45]),
% For strings with width
io:format("width4: |~6s|~6s|~n", ["foo", "b"]),
% Left-justified strings
io:format("width5: |~-6s|~-6s|~n", ["foo", "b"]),
% To format a string without printing, use io_lib:format
S = io_lib:format("sprintf: a ~s", ["string"]),
io:format("~s~n", [S]),
% To print to standard error, use io:format(standard_error, ...)
io:format(standard_error, "io: an ~s~n", ["error"]).
This Erlang code demonstrates various string formatting techniques similar to those shown in the Go example. Note that Erlang uses different formatting specifiers and functions for string formatting, but the general concepts are similar.
To run this program, save it as string_formatting.erl
and use the following commands:
$ erlc string_formatting.erl
$ erl -noshell -s string_formatting main -s init stop
This will compile the Erlang file and run the main
function, displaying the formatted output.