晶体中的对象数组
初学者问题:
如何用晶体中的结构制作一系列对象?还是如何在晶体中制作一系列对象?我正在尝试模仿GO代码。
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",
},
}
更改为课程可以使我返回一个新对象。我敢肯定,在晶体中制作新对象的错误方法是错误的?然后,我可以在数组中添加对象。
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以写作
,也可以简单地执行此操作,然后让Crystal识别类型:
最接近原件的是
编辑:如果您需要JSON,则需要实现它,例如 with-to-json“ rel =“ rel =“ nofollow noreferrer”>。最简单的是
包括JSON :: serializable
:You can write
or you can simply do this, and let Crystal recognise the type:
The closest to the original is
EDIT: If you need JSON, you need to implement it, as described in the documentation. The easiest is to
include JSON::Serializable
:似乎我想要的是,与Go中的结构版本不一样,是一系列哈希,这反过来是一系列对象,因为一切都是晶体中的对象?*。
It seems really what I wanted, and what was not the same as the struct version in go was an Array of Hashes, which in turn is an Array of Objects, as everything is an Object in Crystal?*.