不能在match中调用远程函数:Foreach循环 [英] cannot invoke remote function inside match : Foreach loop
问题描述
我正在尝试在for-each循环中设置User模型的某些属性,但是我一直在跟踪错误
I'm trying to set some property of User model inside a for-each loop, But I keep getting following error
在匹配中不能调用远程函数x.token / 0
(elixir)src / elixir_fn.erl:9::elixir_fn.translate / 3中的匿名fn / 3
(stdlib) list.erl:1353::lists.mapfoldl / 3
(elixir)src / elixir_fn.erl:14::elixir_fn.translate / 3
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
方法:
Enum.each(users, fn(user) ->
user.token = Comeonin.Bcrypt.hashpwsalt(to_string(user.id))
end)
推荐答案
这里有一些问题。 =
运算符是 match 运算符,不是赋值。用语法的方式来解释错误,这看起来像是匹配项左侧的函数调用,这是不允许的。
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.
但这还不包括您的实际目标。如果要使用新的bcrypt信息更新一组用户模型,则需要使用map函数:
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)
您必须记住Elixir中的所有内容都是不可变的。
You have to remember that everything in Elixir is immutable.
这篇关于不能在match中调用远程函数:Foreach循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!