cannot invoke remote function inside match : Foreach loop

社会主义新天地 提交于 2019-12-10 03:31:18

问题


I'm trying to set some property of User model inside a for-each loop, But I keep getting following error

cannot invoke remote function x.token/0 inside match (elixir) src/elixir_fn.erl:9: anonymous fn/3 in :elixir_fn.translate/3 (stdlib) lists.erl:1353: :lists.mapfoldl/3 (elixir) src/elixir_fn.erl:14: :elixir_fn.translate/3

Method:

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

回答1:


There are a few issues here. The = operator is the match operator, it is not assignment. To explain the error, syntax-wise, this looks like function invocation on the left hand side of a match, which is not allowed.

But this is besides the point of your actual goal. If you want a set of user models that are updated with the new bcrypt information, you need to use a map function:

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

You have to remember that everything in Elixir is immutable.



来源:https://stackoverflow.com/questions/35682499/cannot-invoke-remote-function-inside-match-foreach-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!