【问题标题】:How to get struct name in elixir?如何在长生不老药中获取结构名称?
【发布时间】:2016-09-21 13:38:06
【问题描述】:

假设我有一个结构,struct = %MyApp.MyModel{ filled_with_data: "true }

如何获取结构名称(在我的情况下为MyApp.MyModel)?

【问题讨论】:

    标签: elixir


    【解决方案1】:

    你也可以通过模式匹配来获取结构名:

    %name{} = struct
    

    【讨论】:

    • 太棒了,不知道你可以通过模式匹配获得它!
    【解决方案2】:

    它存储在一个名为 __struct__ 的字段中,因此是 struct.__struct__ == MyApp.MyModel

    【讨论】:

      【解决方案3】:

      如果您需要将结构名称作为不带“Elixir”的字符串。前缀,但保留你可以做的任何模块前缀:

      name = your_map.__struct__
             |> Module.split
             |> Enum.join(".")
      

      【讨论】:

      • 对于your_map.__struct__的等价物(其中your_mapEcto.Schema.t结构),我在iex的刚才的结果中没有得到Elixir.前缀。跨度>
      【解决方案4】:

      结构携带__struct__

      其中的字段。所以,

      struct.__struct__
      

      应该这样做

      【讨论】:

      • @Dogbert 是第一个!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-08
      • 2016-02-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多