10

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.

1

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

Comments

6

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.