John Wang
John Wang

Reputation: 4692

Same binary pattern match of elixir got different representations on command line

I'm new to Elixir and confused by the two different outputs of line15 and line17 below, ie., one is 98 and the other is "b"(from the offical document).

These two matchs just do the same thing, since(IMO) <<head, rest::binary>> is identical to <<head::binary-size(1), rest::binary>>. Why they differ on the output? (I know they're same internally)

I'm using Windows OS BTW.

iex(14)> <<head, rest::binary>> = "banana"
"banana"
iex(15)> head
98
iex(16)> <<head::binary-size(1), rest::binary>> = "banana"
"banana"
iex(17)> head
"b"

Upvotes: 0

Views: 52

Answers (1)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121020

The default type for the element in bitstring is integer, but when you explicitly specify it to be pattern-matched as binary, it becomes binary.

iex|1> <<head::integer, rest::binary>> = "banana"
iex|2> head
#⇒ 98
iex|3> <<head>>
#⇒ "b"

Upvotes: 2

Related Questions