假设我有一个结构体,
struct = %MyApp.MyModel{ filled_with_data: "true }
。
如何获取结构体的名称(在我的例子中为MyApp.MyModel
)?
struct = %MyApp.MyModel{ filled_with_data: "true }
。
如何获取结构体的名称(在我的例子中为MyApp.MyModel
)?
它存储在名为__struct__
的字段中,因此struct.__struct__ == MyApp.MyModel
。
您还可以通过模式匹配获取结构名称:
%name{} = struct
name = your_map.__struct__
|> Module.split
|> Enum.join(".")
your_map.__struct__
的等效写法(其中 your_map
是一个 Ecto.Schema.t
结构体),我刚才在 iex
中的结果中没有得到 Elixir.
前缀。 - Kenny Evitt结构体在其中携带__struct__字段。因此,
struct.__struct__
:__struct__
映射键,这是一个实现细节。 - Nathan Long