Macro to create data structures as structs with less boilerplate.
First, add QuickStruct to your mix.exs dependencies:
defdepsdo[{:quick_struct,"~> 0.1"}]endand run $ mix deps.get.
defmoduleUserdouseQuickStruct,[firstname: String.t,name: String.t]endNow you can use User.t in @type and @spec declarations. To create
instances of your data structure, use one of the following options:
iex(3)>User.make("Jon","Adams")%User{firstname: "Jon",name: "Adams"}iex(4)>User.make([name: "Adams",firstname: "Jon"])%User{firstname: "Jon",name: "Adams"}iex(5)>%User{name: "Adams",firstname: "Jon"}%User{firstname: "Jon",name: "Adams"}You can also define a struct without types, for instance:
defmoduleQuickStructTest.PairdouseQuickStruct,[:first,:second]endThe QuickStruct macro is a very shorthand option to define a struct, a
data type and enforce all fields. The User-struct is equivalent to:
@enforce_keys[:firstname,:name]defstruct[:firstname,:name]@typet::%User{firstname: String.t,name: String.t}The macro also provides make-functions as constructors and other functions, see QuickStruct for further documentation. The generated make-functions for the User-struct are equivalent to:
@specmake(String.t,String.t)::User.tdefmake(firstname,name)do%User{firstname: firstname,name: name}end@specmake([firstname: String.t,name: String.t])::User.tdefmake(fields)doKernel.struct!(User,fields)endThe optional argument :predicate can be used to generate a predicate for the struct:
defmoduleUserWithPredicatedouseQuickStruct,[firstname: String.t,name: String.t],predicate: :user?endiex>user=User.make("Jon","Adams")%User{firstname: "Jon",name: "Adams"}iex>User.user?(user)trueiex>User.user?(non_user_struct)falseiex>User.user?(1)falseIf you need plenty of different data structures, you can use
requireQuickStructQuickStruct.define_module(User,[firstname: String.t,name: String.t])QuickStruct.define_module(Pair,[:first,:second])to create a module and the corresponding struct. So this is shorthand for:
defmoduleUserdouseQuickStruct,[firstname: String.t,name: String.t]enddefmodulePairdouseQuickStruct,[:first,:second]endCopyright © 2021 Active Group GmbH
This work is free. You can redistribute it and/or modify it under the terms of the MIT License. See the LICENSE file for more details.