gpt4 book ai didi

elixir - 如何检查 map 是否也是结构?

转载 作者:行者123 更新时间:2023-12-04 02:32:35 25 4
gpt4 key购买 nike

在 Elixir 中,我可以检查变量是否为 mapstruct , 调用 Kernel.is_map/1 这是有道理的,因为 Structs are Maps underneath ,但我想区分两者。我知道我可以调用__struct__在 Struct 上获取它的模块名称,但在法线贴图上调用它会抛出:

** (KeyError) key :__struct__ not found in: %{}

所以我的问题是, 如何检查变量是映射还是结构?

示例用例:

# I want to handle struct and map inputs differently in my Module

defmodule DifferentThings do
def do_something(arg) when is_map(arg) do
# Do something with Maps
end

def do_something(arg) when is_struct(arg) do
# But handle Structs differently
# Issue is, `is_struct` does not exist
end
end

最佳答案

通常检查 map 是否是一个结构:

Map.has_key?(struct, :__struct__)

对于不同的方法声明(更通用的方法是第二种):
defmodule DifferentThings do
def do_something(%{__struct__: _} = arg) do
# ...
end

def do_something(arg) when is_map(arg) do
# ...
end
end

关于elixir - 如何检查 map 是否也是结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39757796/

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