Taking address of a struct

Pls see code sample below (with compile error)

How come i can take the address of a struct variable (see A), but not take the address of the value return by a constructor (see B),
[Edit] see C & D - which takes the addr of a struct literal and compile without error

package main

import "fmt"

type A struct { a int }

func NewA(a int) A { return A{a: a} }

func main() {
	a := NewA(10)
	aa_1 := &a // A.  Compiles ok

	// compile error: invalid operation: cannot take address of NewA(20) (value of type A)
	aa_2 := &(NewA(20))   // B.  why doesn't this work ? 
        aa_3 := &(struct{ int }{100}). // C. compiles ok
        aa_4 := &(A{100}) // D. compiles ok

	fmt.Println(aa_1, aa_2, aa_3, aa_4)

Hi @globalflea,

A return value has no address. It lives on the call stack that gets cleaned up after the function returns to the caller. For this reason, you have to assign it to a variable (that is, to store it in a more permanent place), in order to give it an address that the code can refer to.


Ok, thanks.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.