Search code examples
crystal-lang

Is an empty slice the same as a null pointer?


Is the following empty slice the same as a null pointer?

slice = Slice(UInt8).empty
slice.size # => 0

The source code of #empty implies a null pointer (address 0 and size 0):

  def self.empty
    new(Pointer(T).null, 0)
  end

Solution

  • This is an application of the Null-Object pattern:

    The empty slice can be used in all places that take a reqular slice, without requiring explicit Nil-Checks.

    A similar example would be returning an empty string on nil or having a GuestUser that has the same properties as a regular User.