Go Recursive Structs

While working on a Telegram bot, I came across a problem where I had to use an entity Message inside a Message making it recursive. Telegram API Spec

In Go, creating a struct is done as follows with is simple and elegant.

type Message struct {
    ID int64 `json:"id"`
    // ...
    ReplyToMessage Message `json:"reply_to_message,omitempty"`
    // ...
}

Now using Message type inside itself will give an error.

illegal cycle in declaration of Message

I am still learning so I wasn’t sure how to fix that, but then I saw some examples that use a pointer instead of a value type, and it worked.

type Message struct {
    ID int64 `json:"id"`
    // ...
    ReplyToMessage *Message `json:"reply_to_message,omitempty"`
    // ...
}

At the end no errors and JSON parsing was working fine.

After a while I understood why that was happening. In Go, when we declare a type e.g. var m Message it will initialize it with default values, like m := Message{}. Which creates a problem and internally if we have used Message inside Message it will constantly try to declare it and creates a cycle in declaration.

Unlike var m Message with pointer type var m *Message it will initialize it with nil that will make it work in the first initialization of Message so no cyclic declaration.

I see it as an absolute win GIF featuring Professor Hulk