Method Has Pointer Receiver Error


StackOverflow Reference

If an interface variable is assigned with a non-pointer value of a concrete type. There will be an error like:

./main.go:31:4: cannot use x (type X) as type Y in assignment:
    Foo does not implement Y (Z method has pointer receiver)

The example code is as the following:

package main

import (
    "fmt"
)

type Cas interface {
    Bar()
}

type Foo struct {
    G int
}

func (f *Foo) Add() {
    f.G = f.G + 10
}

// (1/3) If this function has a pointer receiver that an interface requires
func (f *Foo) Bar() {
    fmt.Println(f.G)
}

func main() {
    // (2/3) Then this variable has to be initiated as a pointer
    f := &Foo{G: 10}

    f.Bar()
    f.Add()

    var c Cas
    // (3/3) In order to be assigned to an interface that requires Bar() function
    c = f

    c.Bar()
}

Run this in playground