-1

If I use pointer receiver, the following code has exception at a=v since it is defined on pointer v, it makes sense.

package main
import (
    "fmt"
    "math"
)

type Abser interface {
    Abs(x int) float64 //all types needs to implement this interface
}

type Vertex struct {
    X float64
}

func (v *Vertex) Abs(x int) float64 {
    return math.Abs(float64(x))
}


func main() {

    /*define the interface and assign to it*/
    var a Abser
    v := Vertex{-3}
    a = &v
    fmt.Println(a.Abs(-3))

    a = v
    fmt.Println(a.Abs(-3))
}

But if I change the function of Abs to

func (v Vertex) Abs(x int) float64 {
    return math.Abs(float64(x))
}

both a=v and a=&v works, what is the reason behind that?

william007
  • 17,375
  • 25
  • 118
  • 194
  • Both functions are same? – Shubham Srivastava Oct 01 '20 at 04:12
  • @william007 I am looking for right resource to tag here – Shubham Srivastava Oct 01 '20 at 04:42
  • 2
    Do any of these answer your question: [Why can we assign a struct pointer to an interface variable even though the struct pointer does not implement the interface?](https://stackoverflow.com/questions/63995894/); [Why can't I assign type's value to an interface implementing methods with receiver type pointer to that type?](https://stackoverflow.com/questions/38166925/), – Charlie Tumahai Oct 01 '20 at 04:56
  • 1
    Does this answer your question? [Why can we assign a struct pointer to an interface variable even though the struct pointer does not implement the interface?](https://stackoverflow.com/questions/63995894/why-can-we-assign-a-struct-pointer-to-an-interface-variable-even-though-the-stru) – Marc Oct 01 '20 at 07:01

1 Answers1

1

Understand it like this as I do not have right resources to quote in answer; Go is happy to pass a copy of pointer struct as value when interface is implemented on value, you can check this by printing the address of variable; This is due to the fact that this operation is considered safe and cannot mutate the original value;

Shubham Srivastava
  • 1,807
  • 1
  • 10
  • 17