This is the 11th day of my participation in Gwen Challenge
Every program needs memory to run.
In Go, developers only need to declare variables, and Go automatically allocates memory for responses based on the type of variables. Memory is divided into two parts:
- Stack memory, go language management, allocation and release
- Heap memory, developers need to pay attention to
Declare a variable
var s string // Zero is ""
var sp *string // Zero is nil
Copy the code
Only declare variables, no initialization, values default to zero
Variable assignment
// Declare direct initialization
var s string ="hello"
// declare and then initialize
var s string
s = "hello"
// Simple declaration
s := "hello"
Panic: Runtime error: invalid memory address or nil dereference
var sp * string
*sp = "hello"
Copy the code
Value type, no direct assignment when initialized, no problem
Pointer type. If no memory is allocated, the default zero value is nil. Memory that is not pointed to will not be used. So the above method will report an error
Pointer variables must be declared, allocated, and initialized at declaration time. The GO language does not automatically allocate memory when pointer types are declared, so assignment cannot be performed.
Memory can be allocated using either the new or make functions
The new function
The new function allocates memory and returns a pointer to that memory
The new function only allocates memory and clears it, returning a pointer to a value of zero of the corresponding type.
Typically used when a return pointer needs to be displayed
type person struc{
name string
age int
}
// Factory function that builds different *person variables with different arguments
func New(name string, age int) *person{
p := new(person)
p.name = name
p.age = age
return &p
}
Copy the code
Make function
Only used for the creation and initialization of slice, chan, and Map built-in types
m := make(map[string]int,10)
Copy the code
The make function is a factory function of the map type. It creates different types of maps based on the type of k-V key-value pairs that pass it, and initializes the size of the map.