Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Array of objects in Crystal

Beginner question:

How to make an Array of objects from a Struct in Crystal? Or how to make an array of objects in Crystal? I am trying to emulate the go code.

struct Book 
   def initialize(
     @Id : Int32,
     @Title : String,
     @Author : String, 
     @Desc : String
   )
   end
 end

 books = [] of Int32 | String <--- This is wrong
 book1 = Book.new(1, "Hello", "Me", "This is a test.")


GO CODE: 

type Book struct {
   Id     int    `json:"id"`
   Title  string `json:"title"`
   Author string `json:"author"`
   Desc   string `json:"desc"`
}

var Books = []models.Book{
   {
       Id:     1,
       Title:  "Golang",
       Author: "Gopher",
       Desc:   "A book for Go",
   },
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can write

books = [] of Book
books << book1

or you can simply do this, and let Crystal recognise the type:

books = [book1]

The closest to the original is

books = [
  Book.new(1, "Hello", "Me", "This is a test.")
]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading