gpt4 book ai didi

elixir - @derive 模块属性的具体语法是什么,它在哪里明确记录?

转载 作者:行者123 更新时间:2023-12-04 15:50:32 27 4
gpt4 key购买 nike

我希望它记录在 Module 中,可能引用了 struct s,但没有快乐。看到它与单个或一系列参数一起使用。到目前为止我能找到的所有变化:

  • 模块名称列表 @derive [MyProtocol, Another]
    (例如, Kernel.defstruct/1 macro doc
    line 65 in ProtocolTest (v1.7.4) )
  • 模块名称
    @derive Inspect
  • 元组以形式@derive {Protocol, key1: :val1, key2: val2}
    (例如, line 550 in InspectTest (v1.8.0-rc.0)
    Phoenix.Param protocol doc )
  • 元组列表 @derive [{Prot1, :options}, {Prot2, key: :val}]
    (例如,line 225 in ProtocolTest (v1.7.4))

  • 我发现唯一提到 @derive 的地方:
  • "Deriving" sectionKernel.defstruct/1 的文档中宏
  • 新的(即 v1.8.0-rc.0)"Deriving" section of Inspect
  • Protocol.derive/3 macro 的文档(在 #7019 中添加)
    (这非常有用,因为使用示例片段可以测试上述所有组合。)


  • 不确定我是否只是忽略了某些东西,因此没有打开问题或拉取请求。

    最佳答案

    文档位于 defstruct那里:

    For each protocol in the @derive list, Elixir will assert there is an implementation of that protocol for any (regardless if fallback to any is true) and check if the any implementation defines a __deriving__/3 callback (via Protocol.derive/3).



    Protocol.derive/3 :

    If your implementation passes options or if you are generating custom code based on the struct, you will also need to implement a macro defined as __deriving__(module, struct, options) to get the options that were passed.



    换句话说, @derive :
  • 接受形式为 {protocol, options} 的元组列表哪里protocol是将被调用的协议(protocol) __deriving__/3optionsterm将作为第三个参数传递
  • protocol (其中 protocol 定义如上 - 描述协议(protocol)模块的原子)与 {protocol, []} 相同
  • 在单个派生模块的情况下,您可以省略将所有内容包装在列表中并直接使用定义


  • 因此,您的示例都可以重写为“更具描述性”,如下所示:
  • 模块名称列表
    @derive [MyProtocol, Another]

    是相同的
    @derive [{MyProtocol, []}, {Another, []}]
  • 模块名称
    @derive Inspect

    是相同的
    @derive [Inspect]

    这与
    @derive [{Inspect, []}]
  • 元组
    @derive {Protocol, key1: :val1, key2: val2}

    是相同的
    @derive [{Protocol, [key1: :val1, key2: val2]}]
  • 元组列表是“规范”形式

  • 我希望这能澄清一切。

    关于elixir - @derive 模块属性的具体语法是什么,它在哪里明确记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54025210/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com