'pass by reference or by value in variable assignment of struct, Golang

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?



Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1