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",
},
}
Changing to a class allows me to return a new object. Which I am sure is the wrong way to make a new object in Crystal? I can then add objects to the array.
class Book
def initialize(id : Int32, title : String, author : String, desc : String)
@id = id
@title = title
@author = author
@desc = desc
end
def object
{
@id,
@title,
@author,
@desc
}
end
end
books = [] of Book <--- HOW TO SET ARRAY OF OBJECTS ON THE TYPE?
book1 = Book.new(1, "Hello", "Me", "This is a test.")
puts book1.object
books << book1.object
puts books