简体   繁体   中英

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.

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's array.concat() ), or is new() not working?

Any other tips on how to improve this code are welcome since I'm obviously new to Go.

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.

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 mgs
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM