drduinfu915094 2018-06-02 15:17
浏览 22
已采纳

在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:

  • 写回答

1条回答 默认 最新

  • dou91808 2018-06-02 16:21
    关注

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里