somejkuser
somejkuser

Reputation: 9040

Returning a pointer in golang

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:

Upvotes: 0

Views: 1269

Answers (1)

Himanshu
Himanshu

Reputation: 12675

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

Upvotes: 1

Related Questions