【问题标题】:Elixir - concat and match combinationElixir - 连接和匹配组合
【发布时间】:2018-06-19 01:46:20
【问题描述】:

这里是灵药新手。试图通过官方文档了解基础知识,我偶然发现了一段我不太理解的代码,也找不到明确搜索它的方法。

iex> "he" <> rest = "hello"
"hello"
iex> rest
"llo"

来源:https://elixir-lang.org/getting-started/binaries-strings-and-char-lists.html

我不明白的是运算符的组合是如何工作的,以及在与“he”模式匹配后,rest 如何分配剩余的字符串。我试图通过如下括号来理解使用优先级:

案例 1 - 显然不一样

iex(1)> "he" <> (rest = "hello")
"hehello"
iex(2)> rest
"hello"

案例 2 - 看起来一样,但我仍然不明白它是如何工作的。

iex(1)> ("he" <> rest) = "hello"
"hello"
iex(2)> rest
"llo"

我不明白,因为 rest 最初在这里是未定义的,这更像是下面的代码,这是前面提到的示例之前的文档中的代码。

iex(1)> <<"he", rest :: binary >> = "hello"
"hello"
iex(2)> rest
"llo"

【问题讨论】:

    标签: elixir


    【解决方案1】:

    "he" &lt;&gt; rest 这是一个模式,它是&lt;&lt;"he", rest::binary&gt;&gt; 的语法糖。

    如果您的意思是您不了解该模式的工作原理,请参阅here 的详细说明。

    简而言之,模式被解析为文字“he”,后跟 0 或更多字节。 rest 通过此模式分配给其余字节。

    binary 类型只允许在模式的末尾,因此以下内容将不起作用:"he" &lt;&gt; ll &lt;&gt; "o"(或 &lt;&lt;"he", ll::binary, "o"&gt;&gt;)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-25
      • 2018-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-25
      • 2017-11-30
      • 2021-04-20
      相关资源
      最近更新 更多