Search code examples
crystal-lang

Clone array of objects Crystal


I need to create a clone of an array of objects in Crystal.

cloned_person_array = persons.clone #[Person, Person, Person]

But I get the following error:

undefined method 'clone' for Person Array(T).new(size) { |i| @buffer[i].clone.as(T) }

I realized that this method is not meant for non-primitives that are defined by the code. The documentation doesn't explicitly exclude it, but it does only show a primitive example.

How do you clone an array of objects in Crystal?

I can imagine performing a .map on the array and then returning a new array that way, but I'm curious if maybe I'm just using the clone method mentioned above incorrectly?


Solution

  • You need to define Person#clone yourself, to allow you to clone Array(Person).

    An easy way to do this is the def_clone macro.

    class Person
      property name : String
    
      def_clone
    end