Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add reference to record to structs section #379

Merged
merged 3 commits into from
Aug 2, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions docs/syntax_and_semantics/structs.md
Original file line number Diff line number Diff line change
Expand Up @@ -93,3 +93,34 @@ ary = [] of Point
If `Point` is inherited, an array of such type should also account for the fact that other types can be inside it, so the size of each element should grow to accommodate that. That is certainly unexpected. So, non-abstract structs can't be inherited from. Abstract structs, on the other hand, will have descendants, so it is expected that an array of them will account for the possibility of having multiple types inside it.

A struct can also include modules and can be generic, just like a class.

## Records

The Crystal [Standard Library](https://crystal-lang.org/api) provides the [`record`](https://crystal-lang.org/api/toplevel.html#record(name,*properties)-macro) macro. It simplifies the definition of basic struct types with an initializer and some helper methods.

```crystal
record Point, x : Int32, y : Int32

Point.new 1, 2 # => #<Point(@x=1, @y=2)>
```

The `record` macro expands to the following struct definition:

```cr
struct Point
getter x : Int32

getter y : Int32

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

def copy_with(x _x = @x, y _y = @y)
self.class.new(_x, _y)
end

def clone
self.class.new(@x.clone, @y.clone)
end
end
```