【问题标题】:cannot invoke remote function inside match : Foreach loop无法在匹配中调用远程函数:Foreach 循环
【发布时间】:2016-02-28 12:25:19
【问题描述】:

我正在尝试在 for-each 循环中设置用户模型的某些属性,但我不断收到以下错误

无法在匹配中调用远程函数 x.token/0 (elixir) src/elixir_fn.erl:9: 匿名 fn/3 在 :elixir_fn.translate/3 (stdlib)lists.erl:1353::lists.mapfoldl/3 (elixir) src/elixir_fn.erl:14: :elixir_fn.translate/3

方法:

Enum.each(users, fn(user) ->
  user.token = Comeonin.Bcrypt.hashpwsalt(to_string(user.id))
end)

【问题讨论】:

  • 你导入 Comeonin.Bcrypt 了吗?如果你这样做了,你可以在没有前缀的情况下调用 hashpwsalt,这可能会导致你出现问题。
  • @GavinBrelstaff 试过了,还是不行
  • 这里 hexdocs.pm/comeonin/Comeonin.Bcrypt.html 说有一个函数 init() - 在调用 hashpwsalt 之前需要调用它吗?

标签: elixir ecto


【解决方案1】:

这里有几个问题。 = 运算符是 match 运算符,它不是赋值。为了解释错误,从语法上看,这看起来像是在匹配左侧的函数调用,这是不允许的。

但这与您的实际目标无关。如果你想要一组用新的 bcrypt 信息更新的用户模型,你需要使用 map 函数:

users = Enum.map(users, fn %User{id: id}=user ->
          %User{user| token: Comeonin.Bcrypt.hashpwsalt("#{id}")}
        end)

您必须记住,Elixir 中的所有内容都是不可变的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多