loading...

Cannot call pointer method on Literal

github logo ・1 min read

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()
}

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

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?

twitter logo DISCUSS
Classic DEV Post from Nov 18 '19

A message from Iran, asking for help on creating better proxies

hitochan profile image