DEV Community

hitochan
hitochan

Posted on

Cannot call pointer method on Literal

I tried to call pointer method on struct literal.

package main

import "fmt"

type Greeter struct {
        name string
}

func (h *Greeter) hello() {
        fmt.Printf("hello %s!\n", h.name)
}

func main() {
        (Greeter{"hitoshi"}).hello()
}
Enter fullscreen mode Exit fullscreen mode

But it fails with the following message.

./hoge.go:14:22: cannot call pointer method on Greeter literal
./hoge.go:14:22: cannot take the address of Greeter literal
Enter fullscreen mode Exit fullscreen mode

Applying & operator makes it work.
According to stackoverflow post, this is because a literal does not have an address.

My question is when we apply & operator on a literal, is a instance of the literal created on memory, and is thus allocated an address?

Top comments (1)

Collapse
 
helpbot profile image
Experimental Help Bot

In Go, it is not possible to call a pointer method on a struct literal directly, as shown in your example. The reason for this is that a struct literal does not have an address in memory, and therefore cannot be passed to a pointer method.

To fix this problem, you can apply the & operator to the struct literal to take its address, like this:

package main

import "fmt"

type Greeter struct {
    name string
}

func (h *Greeter) hello() {
    fmt.Printf("hello %s!\n", h.name)
}

func main() {
    (&Greeter{"hitoshi"}).hello()
}
Enter fullscreen mode Exit fullscreen mode

In this case, the & operator will create a new instance of the Greeter struct in memory and return a pointer to that instance. The pointer can then be passed to the hello method, which is defined as a pointer method, so that it can be called on the struct instance.

In general, it is a good idea to use pointer methods when you need to modify the fields of a struct instance, as this allows you to make changes to the instance without having to pass it by reference. Pointer methods can also be more efficient, as they can avoid the overhead of copying large struct instances when they are passed to a method.

I hope this helps! Let me know if you have any other questions.


I'm an experimental help bot that leverages ChatGPT. As such, the answers I provide may be incorrect, incomplete, or even nonsensical. I am not associated with OpenAI.

Please reply to my comment(s) with your own corrections and feedback.