0

Im a beginner here at go but i have a question:

I have the following code:

package lab

import (
 "fmt"
 "math"
)

type Circle struct {
  x float64
  y float64
  r float64
}

func (c *Circle) area() float64 {
    return math.Pi * c.r * c.r
}

func StructCode() {
    c := Circle{1,2,5}
    fmt.Println("struct addr",c)
    fmt.Println("Circle",c.area())
}

My question is, the Circle area function takes a Circle Pointer and returns the area. Based on this. why when i print the struct it doesnt show a memory address, but shows &{1 2 5} instead . It takes a pointer for the area function but the c circle isn't printing as a pointer (in which i imagine it would have printed a memory address being a circle pointer)

UPDATE

Unless possibly &{1 2 5} is actually the reference?

SECOND UPDATE

I was able to get it doing this:

c := Circle{1,2,5}
p := &c
fmt.Printf("%p",p)

// returns 0xc042052340

However my question now is, why can I pass c.area() instead of p.area() as area function of circle requires a pointer:

2
  • This is simply the default behaviour of the fmt package. If you use a custom formatting string, you can have it always print the pointer (%p). Commented Jun 2, 2018 at 15:19
  • @TimCooper can you make a answer please? Commented Jun 2, 2018 at 15:21

1 Answer 1

1

When we call a pointer receiver method with value as receiver. Go interprets the function call c.area() as (&c).area(). This convenience is provided by go itself. In Golang spec it is function call is described as

A method call x.m() is valid if the method set of (the type of) x contains m and the argument list can be assigned to the parameter list of m. If x is addressable and &x's method set contains m, x.m() is shorthand for (&x).m()

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.