Viewing the Type Hierarchy

By now, you probably suspect that there’s an entire class hierarchy at work behind every Crystal program. It can even be visualized with the crystal hierarchy tool. For example:

$ crystal tool hierarchy virtual.cr

shows all classes and structs from your program as well as the standard library. If you only want a fragment of that tree, your own classes for example, use the -e flag:

$ crystal tool hierarchy -e Document virtual.cr

This produces the following output:

images/classes_and_structs/crystal_tool_hierarchy.png

Let’s make a schema for the most important types, which includes classes as well as structs (for example Int32), that can be abstract or not. Each indentation corresponds to a new subclass level as shown in the figure.

images/classes_and_structs/hierarchy.png

The ultimate superclass is, of course, Object, from which every object inherits lots of methods, such as == and to_s. Then we have a sharp distinction between the objects in the branch inheriting from Value, which are created in stack memory, and the branch inheriting from Reference, which are allocated in heap memory.

Stack memory is much faster to allocate than heap memory, and doesn’t need to be garbage collected, but all values are copied and memory is limited. Heap memory lets a program pass around references instead of values, and is automatically garbage collected. Heap memory is typically used for things like arrays that need to grow dynamically. An Exception is also a heap object.

You can give a type or a group of types a synonym name with alias, as was done here to define a shorter name:

 alias​ PInt32 = Pointer(Int32)
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.35.122