-2
type temp struct{
   val int
}

variable1 := temp{val:5}  // 1
variable2 := &temp{val:6} // 2

In 2, the reference is stored in the variable2.

In 1, does the copy operation is taking place? Or variable1 is also pointed to the same memory portion? or does have a different memory portion than temp{val:5} have?

icza
  • 389,944
  • 63
  • 907
  • 827
Yousuf Ali
  • 23
  • 4
  • Please take the Tour of Go for such basic language fundamentals. There are no references in Go, a pointer is a value. 1 makes a copy. – Volker Mar 08 '22 at 13:08

1 Answers1

2

temp{val:5} is a composite literal, it creates a value of type temp.

In the first example you used a short variable declaration, which is equivalent to

var variable1 = temp{val: 5}

There is a single variable created here (variable1) which is initialized with the value temp{val: 5}.

In the second example you take the address of a composite literal. That does create a variable, initialized with the literal's value, and the address of this variable will be the result of the expression. This pointer value will be assigned to the variable variable2.

Spec: Compositle literals:

Taking the address of a composite literal generates a pointer to a unique variable initialized with the literal's value.

icza
  • 389,944
  • 63
  • 907
  • 827