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",
},
}
>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.")
]