{id: structs}
{id: empty-struct} {i: struct}
{aside} Structs are very powerful constructs in Crystal. Very similar to classes, but they are usually faster.
In the first example we create an empty struct. It does not give as a lot, but we have to start somewhere. {/aside}
{id: struct-initialize} {i: initialize}
{aside}
A more realistic example is a struct that has a method called initialize
that can be used to set the
attributes of the struct. Each variable with a single @
sign in-front of it is an attribute.
We can initialize some of the attributes by values received from the user and some attributes by generating the value ourselves. e.g. by using a Time object, a Random value or generating or computing it in any other way.
We can print the content of the Struct, but we have no way to access the attributes and no way to change them. Hence this struct is immutable. {/aside}
- There is no way to change this struct
- There is no way to access the individual attributes as there are no getters
{id: struct-initialize-shorthand}
{aside} Writing each attribute name 3 times is quite annoying, luckily Crystal provides a shorthand writing mode. {/aside}
{id: struct-immutable-with-getters}
{aside} We can defined methods in the struct to become the getters of the attributes, but this too is boring. {/aside}
{id: struct-immutable-with-getter-macro}
{aside}
We can use the getter
macro to create getters to all of the attributes.
{/aside}
{id: struct-mutable-with-setter}
{id: struct-mutable-with-property-macro}
{id: struct-optional}
{id: struct-with-default}
{id: struct-pass-by-value}
{aside} For immutable structs this is not relevant but when the struct is mutable you have to remember that it is passed by value to functions. That is, the function receives a copy of the external struct. Any changes made to the struct inside the function will be lost when you leave the function. {/aside}
{id: struct-from-json} {i: JSON::Serializable}
{id: struct-from-json-upper-case}
- We cannot have attributes starting with upper case so we have to convert the field names to lowercase:
- Using attribute annotation
{id: struct-from-json-and-initialize} {i: initialize}
{id: struct-from-json-manual-parsing} {i: include} {i: JSON::PullParser}
{id: struct-multi-level-manually}
{id: struct-multi-level-from-json}
{id: struct-from-json-with-extra-data}
{id: struct-from-json-missing-data}
{id: struct-extend-struct}
{id: struct-extend-other-structs}