How to create a dynamic function name using Elixir macro?

前端 未结 3 1028
忘掉有多难
忘掉有多难 2020-12-30 19:12

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         


        
3条回答
  •  春和景丽
    2020-12-30 19:53

    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
    

提交回复
热议问题