In Elixir, I can check if a variable is mapor struct, by calling Kernel.is_map/1, which makes sense, because Structures are the cards below , but I would like to distinguish between them. I know that I can call __struct__Struct to get its module name, but calling it on a regular map:
map
struct
Kernel.is_map/1
__struct__
** (KeyError) key :__struct__ not found in: %{}
So my question is: How to check if a variable is a map or a structure?
Usage example:
# 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
In general, check if map is a structure:
Map.has_key?(struct, :__struct__)
For different method declarations (more general method two):
defmodule DifferentThings do def do_something(%{__struct__: _} = arg) do # ... end def do_something(arg) when is_map(arg) do # ... end end
,
defmodule DifferentThings do def do_something(arg = %_x{}) do IO.puts "This is a struct" end def do_something(arg = %{}) do IO.puts "This is a map" end end
Map vs Struct , .
defmodule Guard do def foo(%{:__struct__ => x }) do Struct end def foo(x) when is_map x do Map end end
keys Map.keys/1.
keys
Map.keys/1
map struct is_map/1 true, :
is_map/1
Map.keys(%{}) will return []
Map.keys(struct)
, . [:__struct__, :name, :age].
[:__struct__, :name, :age]
, :
:__struct__ in Map.keys(struct).
, is_struct .
is_struct
Source: https://habr.com/ru/post/1656150/More articles:https://translate.googleusercontent.com/translate_c?depth=1&pto=aue&rurl=translate.google.com&sl=ru&sp=nmt4&tl=en&u=https://fooobar.com/questions/1656145/cloud-speech-api-return-code-unauthenticated-cause-javaioioexception-error-getting-access-token-for-service-account&usg=ALkJrhgcytITu_j0ZQ8Ox2isUQS4n5Q6AgCustom Angular 2 directive not working - angularHow to stop Jackson YAML script writer from quoting values - javaImprove LIKE Reverse Query Performance - sqlHow to implement Sequence (to enable Swift for-in syntax) from Objective-C? - objective-cUsing python queries and beautiful soup to pull text - pythonНастройка веб-сервера apache на mac os Sierra (macbook pro 13 2014) - apacheRespond to initial Facebook API requests - react-nativeMake code analyzers ignore AssemblyInfo.cs - c #The order of type arguments in indexed vectors - haskellAll Articles