我正在阅读 Elixir 入门文档,但遇到了一些我不理解输出的内容。在下面的例子中,我不明白为什么 rest
最终成为“llo”或因此第一个结果如何,结果为“hello”而不是“hehello”。
iex> "he" <> rest = "hello"
"hello"
iex> rest
"llo"
最佳答案
这是 Elixir 的方式的结果 =
作品。这不会评估为:
"he";
rest = "hello";
不,它会进行模式匹配。 From the docs:
In this chapter, we will show how the = operator in Elixir is actually a match operator and how to use it to pattern match inside data structures.
(强调我的。)我链接的章节解释了
=
与其他语言相比,Elixir 对符号的处理方式有所不同,并解释了您所看到的有些奇怪的行为。=
符号必须两边相等。已经看到右侧,我们有一个值为“hello”的字符串。因此,左边一定是字符串和还有具有值“你好”。左边的变量是rest。 "he" + rest = "hello"
.这个方程有一个唯一的解 -> "he" + "llo" = "hello"
.最后,我们可以得出结论 rest = "llo"
.
关于elixir - 为什么值 rest 包含值 "llo",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33161439/