- Mastering Elixir
- André Albuquerque Daniel Caixinha
- 242字
- 2021-08-05 10:42:47
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?.
iex> x = y = 100
100
iex> x
100
iex> y
100
- Advanced Quantitative Finance with C++
- Testing with JUnit
- 新一代通用視頻編碼H.266/VVC:原理、標準與實現
- Go語言高效編程:原理、可觀測性與優化
- VMware vSphere 6.7虛擬化架構實戰指南
- 零基礎學MQL:基于EA的自動化交易編程
- 精通Python自然語言處理
- Java Web程序設計任務教程
- C語言程序設計實訓教程與水平考試指導
- Django 5企業級Web應用開發實戰(視頻教學版)
- Visual C++從入門到精通(第2版)
- 軟件設計模式(Java版)
- 面向對象程序設計及C++實驗指導(第3版)
- Go語言Hyperledger區塊鏈開發實戰
- Java王者歸來:從入門邁向高手