[英]How to add a struct to an array of structs in Go
In golang I'm trying to make an array of messages, and the ability to easily add a new "object" to the array. 在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)
}
When building I get an error that says: 构建时我收到一条错误消息:
cannot use msg (type *Message) as type Message in append
不能使用msg(类型*消息)作为附加类型的消息
Why is append()
not working (as I might expect from JavaScript's array.concat()
), or is new()
not working? 为什么
append()
不起作用(正如我对JavaScript的array.concat()
期望的array.concat()
),或者new()
不起作用?
Any other tips on how to improve this code are welcome since I'm obviously new to Go. 关于如何改进此代码的任何其他提示都是受欢迎的,因为我显然是Go的新手。
Change these 3 lines 改变这3行
var msg = new(Message)
msg.Name = "Carol"
msg.Content = m
to 至
msg := Message{
Name: "Carol",
Content: m,
}
and everything should work. 一切都应该有效。
new
creates a pointer to Message
. new
创建一个指向Message
的指针。 Your slice is not a slice of Message pointers, but a slice of Messages. 您的切片不是Message指针的一部分,而是一片Message。
In your code, Messages
is a slice of Message
type, and you are trying to append a pointer of Message
type ( *Message
) to it. 在您的代码中,
Messages
是Message
类型的一部分,您尝试将Message
类型( *Message
)的指针附加到它。
You can fix your program by doing the following: 您可以通过执行以下操作来修复程序:
func addMessage(m string) {
var msg = new(Message) // return a pointer to msg (type *msg)
msg.Name = "Carol"
msg.Content = m
Messages = append(Messages, *msg) // use the value pointed by mgs
}
Alternatively, you can declare Messages
as a slice of *Message
: 或者,您可以将
Messages
声明为*Message
的片段:
var Messages = []*Message{
&Message{ // Now each entry must be an address to a Message struct
Name: "Alice",
Content: "Hello Universe",
},
&Message{
Name: "Bob",
Content: "Hello World",
},
}
In above case, addMessage
wouldn't require any changes. 在上面的例子中,
addMessage
不需要任何更改。 But you'll have to modify Messages
access everywhere else. 但是你必须在其他地方修改
Messages
访问权限。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.