abstract struct Struct

Overview

Struct is the base type of structs you create in your program. It is set as a struct's superstruct when you don't specify one:

struct Foo # < Struct
end

Structs inherit from Value so they are allocated on the stack and passed by value. For this reason you should prefer using structs for immutable data types and/or stateless wrappers of other types.

Mutable structs are still allowed, but code involving them must remember that passing a struct to a method actually passes a copy to it, so the method should return the modified struct:

struct Mutable
  property value

  def initialize(@value)
  end
end

def change_bad(mutable)
  mutable.value = 2
end

def change_good(mutable)
  mutable.value = 2
  mutable
end

mut = Mutable.new 1
change_bad(mut)
mut.value # => 1

mut = change_good(mut)
mut.value # => 2

The standard library provides a useful record macro that allows you to create immutable structs with some fields, similar to a Tuple but using names instead of indices.

Direct Known Subclasses

Defined in:

struct.cr

Instance Method Summary

Instance methods inherited from struct Value

==(other) ==

Instance methods inherited from class Object

!=(other) !=, !~(other) !~, ==(other) ==, ===(other)
===(other : YAML::Any)
===(other : JSON::Any)
===
, =~(other) =~, class class, clone clone, crystal_type_id crystal_type_id, dup dup, hash hash, inspect
inspect(io : IO)
inspect
, itself itself, not_nil! not_nil!, tap(&block) tap, to_json to_json, to_pretty_json(io : IO)
to_pretty_json
to_pretty_json
, to_s
to_s(io : IO)
to_s
, to_yaml(io : IO)
to_yaml
to_yaml
, try(&block) try

Class methods inherited from class Object

==(other : Class) ==, ===(other) ===, cast(other) : self cast, from_json(string_or_io) : self from_json, from_yaml(string : String) : self from_yaml, hash hash, inspect(io) inspect, name : String name, to_s(io) to_s, |(other : U.class) |

Instance Method Detail

def ==(other : self) : Bool #

Returns true if this struct is equal to other.

Both structs's instance vars are compared to each other. Thus, two structs are considered equal if each of their instance variables are equal. Subclasses should override this method to provide specific equality semantics.

struct Point
  def initialize(@x, @y)
  end
end

p1 = Point.new 1, 2
p2 = Point.new 1, 2
p3 = Point.new 3, 4

p1 == p2 # => true
p1 == p3 # => false

[View source]
def hash : Int32 #

Returns a hash value based on this struct's instance variables hash values.

See Object#hash


[View source]
def inspect(io : IO) : Nil #

Appends this struct's name and instance variables names and values to the given IO.

struct Point
  def initialize(@x, @y)
  end
end

p1 = Point.new 1, 2
p1.to_s    # "Point(@x=1, @y=2)"
p1.inspect # "Point(@x=1, @y=2)"

[View source]
def to_s(io) #

Same as #inspect(io).


[View source]