new function
We directly declare a pointer type variable p, and then modify the value of the change to "Weike Bird's Nest":
func main() {
var p *string
*p = "微客鸟窝"
fmt.Println(*p)
}
When the program runs, an error will be reported:
panic: runtime error: invalid memory address or nil pointer dereference
This is because if the pointer type variable is not allocated memory, the default value is zero value nil
. It has no memory pointed to, so it cannot be used.
If you want to use it, just allocate a piece of memory to it, you can use the new function:
func main() {
var p *string
p = new(string) //new函数进行内存分配
*p = "微客鸟窝"
fmt.Println(*p)
}
The above example can run normally. What is the purpose of the built-in function new? Source code analysis:
// The new built-in function allocates memory. The first argument is a type,
// not a value, and the value returned is a pointer to a newly
// allocated zero value of that type.
func new(Type) *Type
effect:
- Apply for a piece of memory according to the type passed in, and then return a pointer to this piece of memory
- The data pointed to by the pointer is the zero value of the type
- For example, if the input type is string, then the string pointer is returned, and the data pointed to by the string pointer is an empty string
Variable initialization
After declaring the variables, assigning values to the variables is the so-called initialization.
String type variable initialization:
var s string = "微客鸟窝"
s1 := "微客鸟窝"
Pointer variable initialization
We can define a function to initialize pointer variables
package main
import "fmt"
func main() {
pp:=NewPerson("微客鸟窝",18)
fmt.Println(pp) //&{微客鸟窝 18}
}
type person struct {
name string
age int
}
func NewPerson(name string,age int) *person{
p := new(person)
p.name = name
p.age = age
return p
}
make function
As we have learned above, when using the make function to create a map, the makemap function is actually called:
// makemap implements Go map creation for make(map[k]v, hint).
func makemap(t *maptype, hint int, h *hmap) *hmap{
//省略无关代码
}
What the makemap function returns is *hmap type, and hmap is a structure, which is defined as follows:
// A header for a Go map.
type hmap struct {
// Note: the format of the hmap is also encoded in cmd/compile/internal/gc/reflect.go.
// Make sure this stays in sync with the compiler's definition.
count int // # live cells == size of map. Must be first (used by len() builtin)
flags uint8
B uint8 // log_2 of # of buckets (can hold up to loadFactor * 2^B items)
noverflow uint16 // approximate number of overflow buckets; see incrnoverflow for details
hash0 uint32 // hash seed
buckets unsafe.Pointer // array of 2^B Buckets. may be nil if count==0.
oldbuckets unsafe.Pointer // previous bucket array of half the size, non-nil only when growing
nevacuate uintptr // progress counter for evacuation (buckets less than this have been evacuated)
extra *mapextra // optional fields
}
As you can see, the map keyword is actually very complicated. It contains the size of the map, count, buckets, and so on. If you want to use hmap, just return a *hmap through a simple new function, you also need to initialize it, this is the role of make:
m := make(map[string]int,10)
We found that the make function is very similar to the custom NewPerson function above. In fact, the make function is a factory function of the map type. It can create different types of maps according to the type of key-value pairs passed to it, and can initialize the size of the map at the same time.
The make function is not only a factory function of map type, but also a factory function of chan and slice. It can be used for three types of initialization of slice, chan and map at the same time.
- The new function is only used to allocate memory and clear the memory, which is not commonly used.
- The make function is only used for the creation and initialization of the three built-in types of slice, chan, and map, because the structure of these three types is more complicated. For example, the types of internal elements, the length and capacity of slices, etc. must be initialized in advance for slices.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。