【问题标题】:Map with indifferent key access具有无关密钥访问的映射
【发布时间】:2017-07-21 02:53:54
【问题描述】:

在 Map 上匹配键定义为原子或字符串的最佳做法是什么?

%{"artist" => artist, "track" => track, "year" => year}

%{artist: artist, track: track, year: year}

功能需要同时匹配:

def duplicate_post(%{"artist" => artist, "track" => track, "year" => year}) do
  ...
end

【问题讨论】:

    标签: elixir


    【解决方案1】:

    我能想到的最好方法是定义函数两次,每种输入一次,然后从另一个调用其中一个。

    def duplicate_post(%{"artist" => artist, "track" => track, "year" => year}) do
      duplicate_post(%{artist: artist, track: track, year: year})
    end
    
    def duplicate_post(%{artist: artist, track: track, year: year}) do
      ...
    end
    

    【讨论】:

      【解决方案2】:

      有一个 Elixir 库可以很好地包装映射、结构、列表和元组以提供无关紧要的访问:

      https://github.com/vic/indifferent

      https://hex.pm/packages/indifferent

      【讨论】:

        猜你喜欢
        • 2012-06-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-25
        • 1970-01-01
        • 1970-01-01
        • 2019-04-21
        相关资源
        最近更新 更多