Skip to content

abstract struct Struct
inherits Value

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 : Int32)
  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

Atomic(T) Atomic::Flag BitArray Char::Reader Colorize::Color256 Colorize::ColorRGB Colorize::Object(T) Complex Crystal::CallSignature Crystal::CodeGenVisitor::FunMetadata Crystal::CodeGenVisitor::Handler Crystal::CodeGenVisitor::ModuleInfo Crystal::CodeGenVisitor::StringKey Crystal::Command::CompilerConfig Crystal::Compiler::Result Crystal::Compiler::Source Crystal::Cover Crystal::CrystalPath Crystal::DefInstanceKey Crystal::DefWithMetadata Crystal::DeprecatedAnnotation Crystal::Doc::HeadTemplate Crystal::Doc::JsNavigatorTemplate Crystal::Doc::JsSearchTemplate Crystal::Doc::JsTypeTemplate Crystal::Doc::JsUsageModal Crystal::Doc::JsVersionsTemplate Crystal::Doc::ListItemsTemplate Crystal::Doc::Main Crystal::Doc::MainTemplate Crystal::Doc::Markdown::Parser::CodeFence Crystal::Doc::Markdown::Parser::PrefixHeader Crystal::Doc::Markdown::Parser::UnorderedList Crystal::Doc::MethodDetailTemplate Crystal::Doc::MethodsInheritedTemplate Crystal::Doc::MethodSummaryTemplate Crystal::Doc::OtherTypesTemplate Crystal::Doc::SidebarTemplate Crystal::Doc::SitemapTemplate Crystal::Doc::StyleTemplate Crystal::Doc::TypeTemplate Crystal::ExhaustivenessChecker Crystal::ExhaustivenessChecker::BoolPattern Crystal::ExhaustivenessChecker::EnumMemberNamePattern Crystal::ExhaustivenessChecker::EnumMemberPattern Crystal::ExhaustivenessChecker::TypePattern Crystal::ExhaustivenessChecker::UnderscorePattern Crystal::ExpandResult Crystal::ExpandResult::Expansion Crystal::ExperimentalAnnotation Crystal::Formatter::AlignInfo Crystal::Formatter::HeredocFix Crystal::Formatter::HeredocInfo Crystal::HashLiteral::Entry Crystal::Hook Crystal::InstanceVarsInitializerVisitor::Initializer Crystal::Lexer::LocPopPragma Crystal::Lexer::LocPushPragma Crystal::Lexer::LocSetPragma Crystal::LinkAnnotation Crystal::MacroInterpreter::MacroVarKey Crystal::Matches Crystal::MathInterpreter Crystal::NamedArgumentType Crystal::NamedTupleLiteral::Entry Crystal::Parser::ArgExtras Crystal::Parser::CallArgs Crystal::Parser::Piece Crystal::Parser::Unclosed Crystal::Playground::PlaygroundPage::Resource Crystal::Playground::WorkbookIndexPage::Item Crystal::Program::CompiledMacroRun Crystal::Program::FinishedHook Crystal::Program::MacroRunResult Crystal::Program::RecordedRequire Crystal::Program::RequireWithTimestamp Crystal::Select::When Crystal::TablePrint::Separator Crystal::Token::DelimiterState Crystal::Token::MacroState Crystal::TopLevelVisitor::FinishedHook Crystal::Type::DefInMacroLookup Crystal::TypeDeclarationProcessor Crystal::TypeDeclarationProcessor::Error Crystal::TypeDeclarationProcessor::NilableInstanceVar Crystal::TypeDeclarationProcessor::TypeDeclarationWithLocation Crystal::TypeFilters Crystal::VirtualTypeLookup::Change CSV::Builder::Row CSV::Row CSV::Token Enumerable::Chunk::Alone Enumerable::Chunk::Drop File::Info GC::ProfStats GC::Stats Hash::Entry(K, V) HTTP::FormData::FileMetadata HTTP::FormData::Part HTTP::Headers HTTP::StaticFileHandler::DirectoryListing IO::EncodingOptions JSON::Any JSON::Builder::ArrayState JSON::Builder::DocumentEndState JSON::Builder::DocumentStartState JSON::Builder::ObjectState JSON::Builder::StartState LLVM::ABI::ArgType LLVM::BasicBlock LLVM::BasicBlockCollection LLVM::DIBuilder LLVM::Function LLVM::FunctionCollection LLVM::FunctionPassManager::Runner LLVM::GlobalCollection LLVM::InstructionCollection LLVM::Metadata LLVM::OperandBundleDef LLVM::ParameterCollection LLVM::PassRegistry LLVM::PhiTable LLVM::Target LLVM::TargetData LLVM::Type LLVM::Value Log::Context Log::Emitter Log::Entry Log::Metadata::Value Log::StaticFormatter MIME::MediaType Path Pointer::Appender(T) Process::Tms Range(B, E) Regex::MatchData SemanticVersion SemanticVersion::Prerelease Set(T) Slice(T) Socket::Address Socket::Addrinfo Spec::Example::Procsy Spec::ExampleGroup::Procsy Spec::SplitFilter Time Time::Format Time::Location::Zone Time::MonthSpan Time::Span URI::Params UUID VaList YAML::Any

Methods

#==(other) : Bool

Returns true if this struct is equal to other.

Both structs' 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 : Int32, @y : Int32)
  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

#hash(hasher)

View source

#inspect(io : IO) : Nil

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

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

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

#pretty_print(pp) : Nil

View source

#to_s(io : IO) : Nil

Same as #inspect(io).

View source