【发布时间】:2021-06-17 11:27:05
【问题描述】:
在 golang 中,我正在尝试创建一个消息数组,并能够轻松地将新的“对象”添加到数组中。
type Message struct {
Name string
Content string
}
var Messages = []Message{
{
Name: "Alice",
Content: "Hello Universe",
},{
Name: "Bob",
Content: "Hello World",
},
}
func addMessage(m string) {
var msg = new(Message)
msg.Name = "Carol"
msg.Content = m
Messages = append(Messages, msg)
}
在构建时,我收到一条错误消息:
不能使用 msg (type *Message) 作为类型 Message in append
为什么append() 不起作用(正如我对JavaScript 的array.concat() 所期望的那样),或者new() 不起作用?
欢迎任何其他关于如何改进此代码的提示,因为我显然是 Go 新手。
【问题讨论】:
-
查看是否在 msg 后添加 ... 有帮助 (stackoverflow.com/questions/8461462/…)