Go Value Types and Reference Types
Value Types
Value type variables are allocated directly on the stack when declared, storing the actual value. When a value type variable is assigned or passed as an argument to a function, a copy of the value is made, meaning that modifications to the copy do not affect the original variable.
bool
int8, int16, int32, int64
uint8, uint16, uint32, uint64
float32, float64
complex64, complex128
string
array
// Value Type
a := 10
b := a // Copy of the value, b and a are two independent variables
b = 20 // Modifying b's value does not affect a
fmt.Println("a:", a, "b:", b) // Output: a: 10 b: 20
Reference Types (Pointer Types)
When reference type variables are declared, memory is allocated on the heap to store the variable's memory address (pointer) rather than the actual value. When a reference type variable is assigned or passed as an argument to a function, a copy of this reference is passed, not a copy of the value. This means that multiple reference type variables may point to the same memory address, and modifying one variable can affect all variables pointing to that address.
slice
map
chan
function
interface
pointer
// Reference Type
s1 := []int{1, 2, 3}
s2 := s1 // Copy of the reference (i.e., copy of the address), s2 and s1 point to the same underlying array
s2[0] = 100 // Modifying the first element of s2 also affects s1
fmt.Println("s1:", s1, "s2:", s2) // Output: s1: [100 2 3] s2: [100 2 3]
Stack Memory
- Stack memory is automatically managed by the system, operating in a manner similar to a stack data structure.
- Stack memory is used for storing local variables and parameters of function calls.
- When a function is called, its local variables and parameters are allocated memory on the stack.
- Upon returning from a function, the memory occupied by these local variables and parameters is automatically released.
- Stack memory is typically smaller but has very fast access speeds.
Heap Memory
- Heap memory is managed by the programmer or, if not released by the programmer, may be reclaimed by the operating system or garbage collector at the end of a program.
- When a reference type variable is declared and initialized, memory is allocated on the heap for it, and the address of that memory is assigned to the variable.
- Through reference type variables, you can access and manipulate data on the heap.
- Heap memory is relatively larger but has slower access speeds compared to stack memory.
Take a break
πππ γBTTH Year EP101γXiao Yan upgraded to Dou Zong and found Elder Yao