dgo.a
dgo.a

Reputation: 2764

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

Upvotes: 1

Views: 107

Answers (1)

felixbuenemann
felixbuenemann

Reputation: 639

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.

Upvotes: 0

Related Questions