元组

{ a, b, c } = { "Hello", "World", "!" }    

IO.puts a # Hello
IO.puts b # World
IO.puts c # !

# Tuples of different size won't match:

{ a, b, c } = { "Hello", "World" } # (MatchError) no match of right hand side value: { "Hello", "World" }

阅读文件

模式匹配对于返回元组的文件读取操作很有用。

如果文件 sample.txt 包含 This is a sample text,那么:

{ :ok, file } = File.read("sample.txt")
# => {:ok, "This is a sample text"}

file
# => "This is a sample text"

否则,如果该文件不存在:

{ :ok, file } = File.read("sample.txt")
# => ** (MatchError) no match of right hand side value: {:error, :enoent}

{ :error, msg } = File.read("sample.txt")
# => {:error, :enoent}