Slices in Crystal
Note that while slices are different types than arrays, they are rendered similarly by puts
.
When you run this program, you’ll see output similar to:
In Crystal, arrays are used in a similar way to slices in Go. They are dynamic and can grow or shrink as needed. The Array
class in Crystal provides methods similar to slice operations in Go, such as <<
for appending, []
for accessing elements, and range syntax for slicing.
Crystal’s arrays are type-safe at compile-time, ensuring that all elements in an array are of the same type or a common supertype.
Now that we’ve seen arrays in Crystal, which serve a similar purpose to both arrays and slices in Go, we’ll look at Crystal’s other key built-in data structure: hashes (which are similar to maps in Go).