【问题标题】:Can __using__ insert at end of a module?__using__ 可以插入到模块的末尾吗?
【发布时间】:2016-10-02 22:49:47
【问题描述】:

假设我正在制作一个模块,其中模式匹配是它的大部分功能,例如结构或花哨的 case 语句;有没有办法use Module 可以在其使用的模块的底部 处插入一个子句?这样做的原因是添加,比方说,将捕获与声明的匹配失败的匹配的默认子句。

举一个人为的例子:

defmodule NumberToNumber do
    use SwitchLib, default: 0
#   import SomeMacros

    opt 1, "one"
#   convert("one"), do: 1

    opt 2, "two"
    opt 3, "three"
    opt 4, "four"

    default 0            <-- Can this be procedurally generated?
#   convert(_), do: 0    <--     or this, for that matter,

end

这可能吗,还是我应该以不同的方式解决这个问题?我的后备计划是引用 convert(_) 来尝试 __MODULE__.convert(arg) 本身并独立说明不匹配。

无论如何,编译器是否使上述方法成为可能?

【问题讨论】:

    标签: elixir


    【解决方案1】:

    是的,

    @before_compile 等回调允许您在模块定​​义完成时将代码注入模块。

    除了@before_compile,还有其他有用的模块属性,如@on_definition@after_compile,您可以在docs for the Module module 中了解更多信息。

    所有这些工具都可以与 __using__ 或 vanilla 宏一起使用,以创建动态生成的代码,允许您编写一个循环,为任意范围的 i 创建 opt i 语句。您可以在 Macro moduleMacro.Env 的文档中找到有关宏和编译环境的有用信息。

    【讨论】:

      猜你喜欢
      • 2021-07-20
      • 2019-12-22
      • 1970-01-01
      • 2013-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-15
      相关资源
      最近更新 更多