如何使用Elixir宏创建动态函数名称? [英] How to create a dynamic function name using Elixir macro?
本文介绍了如何使用Elixir宏创建动态函数名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想动态创建一个函数名。我写了这个宏
I want to create a function names dynamically. I wrote this macro
defmacro generate_dynamic(name) do
quote do
def add_(unquote(name)) do
end
end
end
像这样:
defmodule AnotherModule do
generate_dynamic :animal
end
现在,我只定义了 AnotherModule.add _
函数,而我期望 AnotherModule.add_animal
函数。
Now, I only get AnotherModule.add_
function defined, whereas I expect AnotherModule.add_animal
function.
推荐答案
要实现此目的,您可以在:add _
取消引用前的名称。另外,在这种情况下,方法名称后面的括号是必需的,以防止产生歧义。这应该可以解决问题:
To achieve this, you can prepend :add_
to the name before unquoting. Also, the parentheses after the method name in this case are required to prevent ambiguities. This should do the trick:
defmacro generate_dynamic(name) do
quote do
def unquote(:"add_#{name}")() do
# ...
end
end
end
这篇关于如何使用Elixir宏创建动态函数名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文