官术网_书友最值得收藏!

Pattern matching on binaries and strings

The following example shows how you can use pattern matching on binaries:

iex> <<first_byte, second_byte>> = <<100, 200>>
<<100, 200>>
iex> first_byte
100
iex> second_byte
200

As previously stated when describing binaries, this can be incredibly helpful when you're dealing with bytes directly, such as parsing a packet from a given network protocol. By applying pattern matching to binaries, you can extract bits or bytes as necessary, while your code remains extremely expressive.

Since strings are just binaries underneath, we can use the same strategy as we did in the preceding snippet:

iex> <<first_byte, second_byte>> = "YZ"
"YZ"
iex> first_byte
89
iex> second_byte
90

However, this isn't very helpful when dealing with strings, as you're getting the decimal code of the characters in UTF-8 (also, as UTF-8 is a variable width encoding, a code point may take more than one byte). To match on strings, the best approach is to use the functions from the String module, such as starts_with?, ends_with?, or contains?.

As we've explained in the beginning of this section, everything in Elixir is an expression, and in pattern matching, when the match succeeds, the right-hand side of the expression is returned. Due to this behavior and taking into account that Elixir rebinds the variables on the left-hand side, we can write expressions such as the following one, binding multiple variables to the same value:

iex> x = y = 100
100
iex> x
100
iex> y
100
主站蜘蛛池模板: 德保县| 太原市| 密山市| 建始县| 乌拉特后旗| 广平县| 双桥区| 肥西县| 蒲城县| 黄冈市| 宁陕县| 松江区| 田阳县| 二手房| 寻乌县| 康乐县| 临桂县| 兰州市| 沐川县| 措勤县| 尖扎县| 外汇| 辉县市| 咸丰县| 贵阳市| 松江区| 衡水市| 寿宁县| 瑞安市| 涡阳县| 九江县| 尼玛县| 闵行区| 隆安县| 金昌市| 宝坻区| 郧西县| 乌鲁木齐市| 大悟县| 雷波县| 安陆市|