64 views
Skip to first unread message

王晚成

unread,
Jan 19, 2018, 1:26:04 AM1/19/18
to golang-nuts
hello my dear friend Google man:
I have some questions.

type Point struct{
x int
y int
}

func (p *Point) hehe(i int) {
p.x = i
p.y = i
}

func main(){
Point{1,2}.hehe(4) // compile error: can't take address of Point literal
}

The book says that there’s no way to obtain the address of a temporary value.

but
( &Point{1,2}).hehe(4) //sucessed

why & can obtain the address of a temporay value?

thanks

Volker Dobler

unread,
Jan 19, 2018, 1:47:57 AM1/19/18
to golang-nuts
Point{1,2} is not a temporary variable but a literal
and these do have addresses. Just not automatically.

V.

Jan Mercl

unread,
Jan 19, 2018, 2:32:00 AM1/19/18
to Volker Dobler, golang-nuts
On Fri, Jan 19, 2018 at 7:48 AM Volker Dobler <dr.volke...@gmail.com> wrote:

> Point{1,2} is not a temporary variable but a literal
> and these do have addresses. Just not automatically.

Did you mean &Point{1, 2}? Otherwise Point{1, 2} is a non-addressable value like 42. Literals do not have addresses before assigned to an (addressable) variable. The &T{} construct OTOH is an address per-se, not a literal value (but the pointee is).


--

-j

Reply all
Reply to author
Forward
0 new messages