How to add a struct to an array of structs in Go
Solution 1
Change these 3 lines
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
. Your slice is not a slice of Message pointers, but a slice of Messages.
Solution 2
In your code, Messages
is a slice of Message
type, and you are trying to append a pointer of Message
type (*Message
) to it.
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 msg
}
Alternatively, you can declare Messages
as a slice of *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. But you'll have to modify Messages
access everywhere else.
Comments
-
Luke almost 2 years
In golang I'm trying to make an array of messages, and the ability to easily add a new "object" to the array.
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
Why is
append()
not working (as I might expect from JavaScript'sarray.concat()
), or isnew()
not working?Any other tips on how to improve this code are welcome since I'm obviously new to Go.