1. 首页
  2. 主题
  3. Go语言

编译器提示 cannot take the address of XXX literal,但其实可以?

xuchunyang · · 2883 次点击
运行: ```go package main import "fmt" type Point struct { X, Y float64 } func (p *Point) Describe() { fmt.Printf("(%v, %v)\n", p.X, p.Y) } func main() { (&Point{1, 2}).Describe() Point{1, 2}.Describe() } ``` 报 2 个编译错误,都是由 `Point{1, 2}.Describe()` 引起的: ``` ./prog.go:15:13: cannot call pointer method on Point literal ./prog.go:15:13: cannot take the address of Point literal ``` "cannot take the address of Point literal" 很奇怪,上一行中 `&Point{1,2}` 明明取址了,而且也没报错。Spec 中也说了可以取址。这句该怎么理解?是不是为了强行解释"cannot call pointer method on Point literal"? --- https://play.golang.org/p/GRQM-EzMSrz
那是因为你的Point没有实现该方法,需要带&
#1
更多评论
你的receiver 是(p *Point)
#2

用户登录

没有账号?注册

今日阅读排行

    加载中

一周阅读排行

    加载中